日期:2014-05-18 浏览次数:20580 次
--> 测试数据:[tbl]
go
if object_id('[tbl]') is not null 
drop table [tbl]
go
create table [tbl](
[Date] datetime,
[Result] varchar(2)
)
go
insert [tbl]
select '2011-01-01','胜' union all
select '2011-01-02','胜' union all
select '2011-01-03','胜' union all
select '2011-01-03','负' union all
select '2011-01-03','负' union all
select '2011-01-04','胜' union all
select '2011-01-04','胜' union all
select '2011-01-04','胜'
declare @str varchar(1000)
set @str=''
select @str=@str+','+[Result]+'=sum(case when [Result]='
+QUOTENAME([Result],'''')+' then 1 else 0 end)' from tbl
group by [Result]
exec('select convert(varchar(10),[Date],120) as [Date] '+@str+
' from tbl group by convert(varchar(10),[Date],120)')
/*
Date    胜    负
2011-01-01    1    0
2011-01-02    1    0
2011-01-03    1    2
2011-01-04    3    0
*/
------解决方案--------------------
select
 CONVERT(VARCHAR(10) , DATE, 120),
 sum(case when result='胜' then 1 else 0 end) as '胜', 
 sum(case when result='负' then 1 else 0 end) as '负' 
from tbl group by CONVERT(VARCHAR(10) , DATE, 120)