Colum case () bag after turning
Sorry if I don't explain very well and the title is not very clear. I am using SQL Server 2005. I have a query with Pivot that works fine, but know that I have to add a new query that gets resuls from the quarter.
This is my request to get the result from the 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;
So, I only know that I want to get four registrars
1 With Month 1+2+3
2 Wint Month 4+5+6
3 With Month 7+8+9
4 Wint Month 10+11+12
I tried with UNION ALL but didn't work as I expected. Any help would be appreciated and sorry for my poor english and explanation.
This is my request with no result
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
Thanks in advance.
+3
source to share
2 answers
Try something like .....
; 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
+2
source to share
You can GROUP BY
number the quarter, i.e. mes - (mes - 1) % 3
, in the result set 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
0
source to share