当前位置: 代码迷 >> Sql Server >> [求sql语句]标题不知道如何描述,请进来看详情
  详细解决方案

[求sql语句]标题不知道如何描述,请进来看详情

热度:37   发布时间:2016-04-27 13:56:54.0
[求sql语句]标题不知道怎么描述,请进来看详情。
需求如下:

有一张表Table:
  Date Result
2011-01-01 胜
2011-01-02 胜
2011-01-03 胜
2011-01-03 负
2011-01-03 负
2011-01-04 胜
2011-01-04 胜
2011-01-04 胜

select出来的结果如下:
  Date 胜 负
2011-01-01 1 0
2011-01-02 1 0
2011-01-03 1 2
2011-01-04 3 0


谢谢各位!

------解决方案--------------------
SQL code
--> 测试数据:[tbl]goif object_id('[tbl]') is not null drop table [tbl]gocreate table [tbl]([Date] datetime,[Result] varchar(2))goinsert [tbl]select '2011-01-01','胜' union allselect '2011-01-02','胜' union allselect '2011-01-03','胜' union allselect '2011-01-03','负' union allselect '2011-01-03','负' union allselect '2011-01-04','胜' union allselect '2011-01-04','胜' union allselect '2011-01-04','胜'declare @str varchar(1000)set @str=''select @[email protected]+','+[Result]+'=sum(case when [Result]='+QUOTENAME([Result],'''')+' then 1 else 0 end)' from tblgroup by [Result]exec('select convert(varchar(10),[Date],120) as [Date] [email protected]+' from tbl group by convert(varchar(10),[Date],120)')/*Date    胜    负2011-01-01    1    02011-01-02    1    02011-01-03    1    22011-01-04    3    0*/
------解决方案--------------------
SQL code
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)
  相关解决方案