SQL应该怎么groupby 并分段取值。
表结构
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),
[21-25] = sum(CASE WHEN DAY([datetime]) BETWEEN 21 AND 25 THEN sale ELSE 0 end),
[26-月末] = sum(CASE WHEN DAY([datetime]) BETWEEN 26 AND 31 THEN sale ELSE 0 end)
FROM #temp
WHERE MONTH([datetime]) = 1
GROUP BY province
ORDER BY SUM(sale) DESC
--如果楼主非要自己的那个显示方式,再加些“口水”字段即可,细节,自己改
SELECT TOP(2)
province,
总计=SUM(sale),
dateRang1 = '[1-5]',
[1-5] = sum(CASE WHEN DAY([datetime]) BETWEEN 1 AND 5 THEN sale ELSE 0 end),
dateRang2 = '[6-10]',
[6-10] = sum(CASE WHEN DAY([datetime]) BETWEEN 6 AND 10 THEN sale ELSE 0 end),
dateRang3 = '[11-15]',
[11-15] = sum(CASE WHEN DAY([datetime]) BETWEEN 11 AND 15 THEN sale ELSE 0 end),
dateRang4 = '[16-20]',
[16-20] = sum(CASE WHEN DAY([datetime]) BETWEEN 16 AND 20 THEN sale ELSE 0 end),
dateRang5 = '[21-25]',
[21-25] = sum(CASE WHEN DAY([datetime]) BETWEEN 21 AND 25 THEN sale ELSE 0 end),
dateRang6 = '[26-月末]',
[26-月末] = sum(CASE WHEN DAY([datetime]) BETWEEN 26 AND 31 THEN sale ELSE 0 end)
FROM #temp
WHERE MONTH([datetime]) = 1
GROUP BY province
ORDER BY SUM(sale) DESC