日期:2014-05-18  浏览次数:20538 次

一个sql题,各位帮帮忙谢谢啦。
只有一个表
create table FS
(
Id int primary key identity(1,1),
Dates date not null,
fs char(2) not null,
)
insert into FS values('2011-05-01','胜')
insert into FS values('2011-05-02','胜')
insert into FS values('2011-05-01','负')
insert into FS values('2011-05-02','胜')
insert into FS values('2011-05-01','负')

怎样用sql语句查询出按日期分组胜负数各是多少啊。不知道给位看的明白不,我描述的这个。大家帮帮忙啦。

------解决方案--------------------
SQL code

create table FS
(
Id int primary key identity(1,1),
Dates datetime not null,
fs char(2) not null,
)
insert into FS values('2011-05-01','胜')
insert into FS values('2011-05-02','胜')
insert into FS values('2011-05-01','负')
insert into FS values('2011-05-02','胜')
insert into FS values('2011-05-01','负')

SELECT Dates,
sum(CASE WHEN fs='胜' THEN 1 ELSE 0 END) AS 胜的数量, 
sum(CASE WHEN fs='负' THEN 1 ELSE 0 END) AS 负的数量 
FROM FS GROUP BY Dates
/*
Dates                   胜的数量        负的数量
----------------------- ----------- -----------
2011-05-01 00:00:00.000 1           2
2011-05-02 00:00:00.000 2           0
*/

------解决方案--------------------
SQL code
create table FS
(
Id int primary key identity(1,1),
Dates date not null,
fs char(2) not null,
)
insert into FS values('2011-05-01','胜')
insert into FS values('2011-05-02','胜')
insert into FS values('2011-05-01','负')
insert into FS values('2011-05-02','胜')
insert into FS values('2011-05-01','负')


select dates,FS,COUNT(fs) counts from FS group by Dates,fs 
/*
dates    FS    counts
2011-05-01    负    2
2011-05-01    胜    1
2011-05-02    胜    2
*/