让我们考虑一下这样的问题:
SELECT *
FROM (
SELECT
YEAR(OrderDate) [Year],
MONTH(OrderDate) [Month],
SubTotal
FROM Sales.SalesOrderHeader
) TableDate
PIVOT (
SUM(SubTotal)
FOR [Month] IN (
[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]
)
) PivotTable
它返回一个如下所示的表:
year 1 2 3 4 5 6 ... 12 //MONTH
2001 100 100 100 100 100 100 100
我们如何对列进行分组并在表单中返回结果,例如:
year 1-3 4-5 5-10 11-12 //Group the columns!
2001 300 200 500 200
我需要一个T-SQL查询来执行此操作。我已经检查了动态查询执行但它也没有多大帮助..
答案 0 :(得分:4)
在子查询中,首先将您的月份放在正确的存储桶中,然后在该表上执行数据透视。
SELECT *
FROM (
SELECT
YEAR(OrderDate) [Year],
CASE WHEN MONTH(OrderDate)<=3 THEN '1-3'
WHEN MONTH(OrderDate)<=5 THEN '4-5',
WHEN MONTH(OrderDate)<=10 THEN '6-10',
ELSE '11-12' END [MonthRange]
SubTotal
FROM Sales.SalesOrderHeader
) TableDate
PIVOT (
SUM(SubTotal)
FOR [MonthRange] IN (
['1-3'],['4-5'],['6-10'],['11-12']
)
) PivotTable
答案 1 :(得分:1)
我没有那么多地使用PIVOT(并且这里没有足够的信息来重新创建你的样本),但你不能只说而不是SELECT *:
SELECT [year], [1-3] = [1] + [2] + [3], [4-5] = [4] + [5], ...
FROM ( SELECT YEAR ...) TableDate
PIVOT ( SUM(SubTotal) FOR ...) PivotTable;
修改强> 为@ t-clausen.dk添加一个简单的工作示例:
CREATE TABLE #x([year] INT, [month] INT, total INT);
INSERT #x SELECT 2011, 1, 15
UNION ALL SELECT 2011, 2, 20
UNION ALL SELECT 2011, 2, 30
UNION ALL SELECT 2011, 3, 15
UNION ALL SELECT 2011, 4, 22
UNION ALL SELECT 2011, 5, 13
UNION ALL SELECT 2011, 6, 22
UNION ALL SELECT 2011, 7, 12
UNION ALL SELECT 2011, 8, 14
UNION ALL SELECT 2011, 9, 30
UNION ALL SELECT 2011, 10, 30
UNION ALL SELECT 2011, 11, 20
UNION ALL SELECT 2011, 12, 45;
SELECT
[year],
[1-3] = [1] + [2] + [3],
[4-5] = [4] + [5],
[6-10] = [6] + [7] + [8] + [9] + [10],
[11-12] = [11] + [12]
FROM ( SELECT [year], [month], total FROM #x ) AS TableDate
PIVOT (
SUM(total)
FOR [month] IN
(
[1], [2], [3], [4],
[5], [6], [7], [8],
[9],[10],[11],[12]
)
) AS PivotTable
ORDER BY [year];
DROP TABLE #x;