当前位置: 代码迷 >> Sql Server >> group by 的小疑点
  详细解决方案

group by 的小疑点

热度:89   发布时间:2016-04-27 20:29:19.0
group by 的小问题。
数据
------
id     date               money
1       20070611       100
1       20070612       100
1       20070613       100
2       20070611       100

------
希望通过   "年月 "   来group   by   ,sum(money),而现在的date字段还有   "日 ".

该怎么才能得到
1       200706     300
2       200706     100

------解决方案--------------------
select id,left([date],6) [date],sum(money) [money] from [Table] group by id,left([date],6)
------解决方案--------------------
declare @t table(id int,date char(8),money int)

insert @t
select 1, '20070611 ',100 union all
select 1, '20070612 ',100 union all
select 1, '20070613 ',100 union all
select 2, '20070611 ',100

select
id,
substring(date,1,6) as date,
sum(money) as money
from @t
group by id,substring(date,1,6)
------解决方案--------------------
select id,month = substring(date,1,6),money = sum(money) from table a group by id,substring(date,1,6)
  相关解决方案