日期:2014-05-17  浏览次数:20454 次

按日期汇总的方法
现有数据库tableA ,字段(id(int),  idate (datetime), iweight(decimal))
数据如下:
1, 2013-01-01 ,100.5
2, 2013-01-11 ,110.5
3, 2013-02-01 ,120.5
4, 2013-02-01 ,130.5
5, 2013-03-01 ,1400.5
6, 2013-03-01 ,150.5
7, 2013-04-01 ,60.5
8, 2013-05-01 ,160.5
9, 2013-05-01 ,180.5
10, 2013-06-01 ,190.5
11, 2013-06-01 ,300.5
现需要根据月份进行分别汇总
如输入2~4月,则分别得到:
1 , 2月  ,500
1 , 3月  ,600
1 , 4月  ,880


------解决方案--------------------
----------------------------------------------------------------
-- Author  :DBA_Huangzj(發糞塗牆)
-- Date    :2013-12-31 16:37:59
-- Version:
--      Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64) 
-- Dec 28 2012 20:23:12 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[tableA]
if object_id('[tableA]') is not null drop table [tableA]
go 
create table [tableA]([id] int,[idate] datetime,[iweight] numeric(5,1))
insert [tableA]
select 1,'2013-01-01',100.5 union all
select 2,'2013-01-11',110.5 union all
select 3,'2013-02-01',120.5 union all
select 4,'2013-02-01',130.5 union all
select 5,'2013-03-01',1400.5 union all
select 6,'2013-03-01',150.5 union all
select 7,'2013-04-01',60.5 union all
select 8,'2013-05-01',160.5 union all
select 9,'2013-05-01',180.5 union all
select 10,'2013-06-01',190.5 union all
select 11,'2013-06-01',300.5
--------------开始查询--------------------------

select CONVERT(VARCHAR(2),DATEPART(MONTH,idate))+'月' '月份',SUM(iweight)iweight
from [tableA]
WHERE DATEPART(MONTH,idate) BETWEEN 2 AND 4 
GROUP BY DATEPART(MONTH,idate)
----------------结果----------------------------
/* 
月份   iweight
---- ---------------------------------------
2月   251.0
3月   1551.0
4月   60.5

*/