日期:2014-05-16 浏览次数:20449 次
? 有如下表:
日期(rstime) 结果(result)
2005-05-09 胜
2005-05-09 胜
2005-05-09 负
2005-05-09 负
2005-05-10 胜
2005-05-10 负
2005-05-10 负
如果要生成下列结果,该如何写sql语句?
日期 胜 负
2005-05-09 2 2
2005-05-10 1 2
SELECT RSTIME AS 日期,
MAX(CASE RESULT WHEN '勝' THEN TOTAL ELSE '' END) AS 勝,
MAX(CASE RESULT WHEN '負' THEN TOTAL ELSE '' END) AS 負
FROM
(
SELECT RSTIME,RESULT,COUNT(RESULT) AS TOTAL
FROM DBO.THETABLE
GROUP BY RSTIME,RESULT
) A
GROUP BY RSTIME
create table tt(rstime datetime,result varchar(10))
insert into tt
select '2005-05-09', '胜' union all
select '2005-05-09', '胜' union all
select '2005-05-09', '负' union all
select '2005-05-09', '负' union all
select '2005-05-10', '胜' union all
select '2005-05-10', '负' union all
select '2005-05-10', '负'
go
select rstime,
count(case when result='胜' then 1 else null end) 胜,
count(case when result='负' then 1 else null end) 负
from tt
group by rstime
/*
rstime 胜 负
2005-05-09 00:00:00.000 2 2
2005-05-10 00:00:00.000 1 2
*/
select rstime,
sum(case when result='胜' then 1 else 0 end) 胜,
sum(case when result='负' then 1 else 0 end) 负
from tt
group by rstime
/*
rstime 胜 负
2005-05-09 00:00:00.000 2 2
2005-05-10 00:00:00.000 1 2
*/