读书人

一条sql话语高手挑战一下吧

发布时间: 2013-03-26 09:54:34 作者: rapoo

一条sql语句,高手挑战一下吧


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)
[解决办法]

declare @table1 table(c1 varchar(1),c2 int)
insert into @table1
select 'A', 2 union all
select 'A', 4 union all
select 'B', 0 union all
select 'B', 5 union all
select 'C', 0

select 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)
[解决办法]

declare @table1 table([类型] varchar(1),[数值] int)
insert @table1
select 'A',2 union all
select 'A',4 union all
select 'B',0 union all
select 'B',5 union all
select 'C',0

select top 1 sum(1) as 非零类型个数
from @table1 t group by [类型] having(sum([数值])<>0)
/*
非零类型个数
-----------
2
*/

[解决办法]

declare @table1 table(c1 varchar(1),c2 int)
insert into @table1
select 'A', 2 union all
select 'A', 4 union all
select 'A', 4 union all
select 'B', 0 union all
select 'B', 5 union all
select 'C', 0



select count(distinct case when c2 > 0 then c1 else null end ) as 非零类型个数
from @table1

读书人网 >SQL Server

热点推荐