日期:2014-05-17 浏览次数:20815 次
表结构
province sale datetime
广东 2 2013-01-01 00:00:000
广西 3 2013-01-09 00:00:000
广东 5 2013-01-03 00:00:000
广西 1 2013-01-04 00:00:000
北京 2 2013-01-08 00:00:000
想要的结果
province total dateRang1 sale1 dateRang2 sale2
广东 7 1-5号 7 6-10号 0
广西 4 1-5号 1 6-10号 3
CREATE TABLE #temp
(
province NVARCHAR(100),
sale INT,
[datetime] DATETIME
)
INSERT #temp
select N'广东', '2', '2013-01-01 00:00:000 ' union all
select N'广西', '3', '2013-01-09 00:00:000' union all
select N'广东', '5', '2013-01-03 00:00:000' union all
select N'广西', '1', '2013-01-04 00:00:000' union all
select N'北京', '2', '2013-01-08 00:00:000'
--个人觉得这个结果显示最好
SELECT TOP(2)
province,
总计=SUM(sale),
[1-5] = sum(CASE WHEN DAY([datetime]) BETWEEN 1 AND 5 THEN sale ELSE 0 end),
[6-10] = sum(CASE WHEN DAY([datetime]) BETWEEN 6 AND 10 THEN sale ELSE 0 end),
[11-15] = sum(CASE WHEN DAY([datetime]) BETWEEN 11 AND 15 THEN sale ELSE 0 end),
[16-20] = sum(CASE WHEN DAY([datetime]) BETWEEN 16 AND 20 THEN sale ELSE 0 end),