一条sql语句,高手挑战一下吧
- SQL code
select ____ as 非零类型个数from table1
table1:
类型 数值
A 2
A 4
B 0
B 5
C 0
结果:
非零类型个数
2
解释:
A有非零记录,B有非零记录,C没有非零记录,所以结果是2。
要求:
不能用where条件,但可以用group by和order by,空格可以用count、sum等,查询速度不能太慢。
空格里该怎么写,求教!!
[解决办法]
SUM(CASE WHEN 数值!=0 then 1 else 0 end)
[解决办法]
- SQL code
declare @table1 table(c1 varchar(1),c2 int)insert into @table1select 'A', 2 union allselect 'A', 4 union allselect 'B', 0 union allselect 'B', 5 union allselect 'C', 0select sum(cnt) 非零类型个数 from( select case when max(c2)>0 then 1 else 0 end cnt from @table1 group by c1)t/*非零类型个数-----------2*/
[解决办法]
SUM(CASE WHEN EXISTS(SELECT 1 FROM TABLE1 WHERE 数值<>0) THEN 1 ELSE 0 END)
[解决办法]
- SQL code
declare @table1 table([类型] varchar(1),[数值] int)insert @table1select 'A',2 union allselect 'A',4 union allselect 'B',0 union allselect 'B',5 union allselect 'C',0select top 1 sum(1) as 非零类型个数from @table1 t group by [类型] having(sum([数值])<>0)/*非零类型个数-----------2*/
[解决办法]
- SQL code
declare @table1 table(c1 varchar(1),c2 int)insert into @table1select 'A', 2 union allselect 'A', 4 union allselect 'A', 4 union allselect 'B', 0 union allselect 'B', 5 union allselect 'C', 0select count(distinct case when c2 > 0 then c1 else null end ) as 非零类型个数from @table1