很抱歉,如果我不能很好地解释,标题不是很清楚。 我在使用SQL Server 2005。 我有一个Pivot的查询工作正常,但知道我必须添加一个新的查询,从季度获得结果。
这是我从Month
获取结果的查询 WITH PivotData AS
(
SELECT idWatimetro, mes,ano, valor
FROM E_Registros_Watimetros where ano = 2012
)
SELECT *
FROM PivotData
PIVOT(SUM(valor) FOR idWatimetro IN ([1],[2],[3],[4],[5] AS P order by mes;
所以,只知道我想获得四个注册
1 With Month 1+2+3
2 Wint Month 4+5+6
3 With Month 7+8+9
4 Wint Month 10+11+12
我一直在和UNION ALL一起尝试,但没有按照我的预期工作,任何帮助都会感激不尽,对不起我糟糕的英语和解释。
这是我没有结果的查询
SELECT *
FROM (
SELECT idWatimetro, ano,mes, valor
FROM E_Registros_Watimetros
WHERE (ano = 2012 and mes = 1 ) or (ano = 2012 and mes = 2)or (ano = 2012 and mes = 3)
UNION ALL
SELECT idWatimetro, ano,mes, valor
FROM E_Registros_Watimetros
WHERE (ano = 2012 and mes = 4 ) or (ano = 2012 and mes = 5)or (ano = 2012 and mes = 6)
) AS SourceTable
PIVOT(SUM(valor) FOR idWatimetro IN ([1],[2],[3],[4],[5]))AS P
谢谢高级。
答案 0 :(得分:2)
尝试类似......
; WITH PivotData AS
(
SELECT idWatimetro
,CASE WHEN mes IN (1,2,3) THEN 1
WHEN mes IN (4,5,6) THEN 2
WHEN mes IN (7,8,9) THEN 3
WHEN mes IN (10,11,12) THEN 4
END AS mes
,ano
,valor
FROM E_Registros_Watimetros where ano = 2012
)
SELECT *
FROM PivotData
PIVOT(SUM(valor)
FOR Mes
IN ([1],[2],[3],[4]))p
答案 1 :(得分:0)
您可以在GROUP BY
的结果集上mes - (mes - 1) % 3
四分之一号,即PIVOT
:
WITH PivotData AS
(
SELECT idWatimetro, mes,ano, valor
FROM E_Registros_Watimetros where ano = 2012
),
PivotResult AS
(
SELECT *
FROM PivotData
PIVOT(SUM(valor) FOR idWatimetro IN ([1],[2],[3],[4],[5])) AS P
),
SELECT CASE mes - (mes - 1) % 3
WHEN 1 THEN '1st'
WHEN 4 THEN '2nd'
WHEN 7 THEN '3rd'
ELSE '4th'
END AS quarter,
2012 AS ano, sum([1]) AS [1], sum([2]) AS [2],
sum([3]) AS [3], sum([4]) AS [4], sum([5]) AS [5]
FROM PivotResult
GROUP BY mes - (mes - 1) % 3