日期:2014-05-19  浏览次数:20604 次

99.9%不能解决的sql
如果一个表有字段type,type有值y   or   n,怎么用select语句返回一条记录,该记录包含y的总和,n的总和

------解决方案--------------------
select sum(case type when 'y ' then 1 else 0 end) [Y Total],
sum(case type when 'n ' then 1 else 0 end) [N Total] from tb
------解决方案--------------------
--try


select
sum(case when type= 'y ' then 1 else 0 end),
sum(case when type= 'n ' then 1 else 0 end)
from tbName
------解决方案--------------------
create table T(type char(1))
insert T select 'y '
insert T select 'y '
insert T select 'y '
insert T select 'n '

select
y_count=sum(case when type= 'y ' then 1 else 0 end),
n_count=sum(case when type= 'n ' then 1 else 0 end)
from T

--result
y_count n_count
----------- -----------
3 1

(1 row(s) affected)