晨风

-------------------- 业精于勤,荒于嬉;行成于思,毁于随

导航

SQL中按月进行分组(转)

Posted on 2011-08-24 09:36  shenyixin  阅读(22098)  评论(0编辑  收藏  举报

SQLSERVER中按年月分组

20090514日 星期四 17:06

一个表有三个字段id,dt,d   分别存放id,时间,数值
id    dt    d

1 2004-08-11 12:12:00.000 9
2 2005-09-11 12:08:00.000 2
3 2005-08-11 12:12:00.000 6
4 2005-09-11 12:12:00.000 10
5 2005-08-11 12:12:00.000 0
要求按照时间里的月份分组求d字段和
回答:
   
相应sql如下:

1 ifexists (select*from dbo.sysobjects where id =object_id(N'[dbo].[abc]') andOBJECTPROPERTY(id, N'IsUserTable') =1)
2droptable[dbo].[abc]
3GO
4
5CREATETABLE[dbo].[abc] (
6     [id][int]NOTNULL ,
7     [dt][datetime]NULL ,
8     [d][int]NULL  
9 ) ON[PRIMARY]
10GO
11
12
13insertinto abc (id,dt,d) values(1,'2004-08-11 12:12:00',9)
14insertinto abc (id,dt,d) values(2,'2005-09-11 12:8:00',2)
15insertinto abc (id,dt,d) values(3,'2005-08-11 12:12:00',6)
16insertinto abc (id,dt,d) values(4,'2005-09-11 12:12:00',10)
17insertinto abc (id,dt,d) values(5,'2005-08-11 12:12:00',0)
18insertinto abc (id,dt,d) values(6,'2004-11-2 12:12:00',4)
19insertinto abc (id,dt,d) values(7,'2004-11-10 12:12:00',4)
20insertinto abc (id,dt,d) values(8,'2004-11-30 12:12:00',4)
21
22select*from abc
23selectdatepart(month,dt)as
月份,sum(d) as合计  from abc groupbydatepart(month,dt)
24
25


其实就用了一个DATEPART函数
引申一下:如果统计1234567891011月上旬,11月中下旬,12月的怎么办?
可以这样:

1 selectcasedatepart(month,dt)
2 when11thencasesign(datepart(day,dt)-11) when-1then11else13end
3 elsedatepart(month,dt) endas
月份,
4 sum(d) as统计
5 from abc groupby
6 casedatepart(month,dt)
7 when11thencasesign(datepart(day,dt)-11) when-1then11else13end
8 elsedatepart(month,dt) end

再引申,如果统计把年月作为分组统计的依据可以这样:

selectdatename(year,dt)+datename(month,dt)as年月 ,sum(d) as统计 from abc groupbydatename(year,dt)+datename(month,dt)

最后,明白group by 后面不仅可以跟字段名就可以了。
------------------------------------------------------------------
再问再续:
1
按照旬统计

1 select
2case (datepart(day,dt)-1)/10when0then'
上旬'when1then'中旬'else'下旬'endas,
3sum(d) as统计
4from abc groupby
5case (datepart(day,dt)-1)/10when0then'上旬'when1then'中旬'else'下旬'end


2
按 年+旬 分组统计
select
datename(year,dt)+datename(month,dt)+case (datepart(day,dt)-1)/10 when 0 then '
上旬' when 1 then '中旬' else '下旬' end as 日期, sum(d) as 统计
from abc group by
datename(year,dt)+datename(month,dt)+case (datepart(day,dt)-1)/10 when 0 then '
上旬' when 1 then '中旬' else '下旬' end