日期:2014-05-17  浏览次数:20498 次

请问这条sql语句如何编写?
比如有一张表 t
name   status
001      胜
001      胜
001      胜
001      负
002      胜
002      负

查询结果
name   胜    负
001    3    1
002    1    1


请各位帮帮忙,谢谢O(∩_∩)O~

------解决方案--------------------

select name,sum(case when status='胜' then 1 else 0 end)[胜],sum(case when status='负' then 1 else 0 end)[负] from tb group by name
------解决方案--------------------
还是PIVOT的问题。
我看这里有很多同学对sql 2005以后的新语法认识不足。

create table tablename 
(name varchar(5),status nvarchar(2))
insert tablename values('001',      '胜')
insert tablename values('001',      '胜')
insert tablename values('001',      '负')
insert tablename values('002',      '胜')
insert tablename values('002',      '负')


select * 
from tablename
PIVOT (
count(status) for status in ([胜],[负])
) as PVT
order by name


如果回答正确请自觉访问峰哥的淘宝店,卖男装的。呵呵。
http://jmsail.taobao.com/