Atascado en Unpivot / Pivot Combo SQL Server 2008

I can't seem to get my head around this problem where I think I need a combination of pivot and unpivot in SQL Server 2008:

Tengo una mesa de la siguiente manera:

Sale       | Month | Count  | Budgeted | Actual
------------------------------------------------
NewSale    | 1     | 120    | 45.23    | 50.10
NewSale    | 2     | 30     | 3.10     | 1.2
NewSale    | 3     | 70     | 45.00    | 100.32

I need to pivot so that the months are as columns, but unpivot so I get the Count, Budgeted, Actual as rows, so it is like so...

Type      | 1      | 2     | 3
-----------------------------------
Count     | 120    | 30    | 70
Budgeted  | 45.23  | 3.10  | 45.00
Actual    | 50.10  | 1.2   | 100.32

I've tried this so far, but I can't work out how to put the pivot in there:

select
 *
from YTD
pivot
(
    sum([Count]), sum([Budgeted]), sum([Actual])
    for [Month] in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
)
as figures

This gives me a syntax error as you can't have more than one calculation in the pivot (as far as what I understood from the error.

Ayuda !!!

preguntado el 10 de marzo de 12 a las 13:03

2 Respuestas

declare @T table
(
  Sale varchar(10),
  [Month] int,
  [Count] int,
  Budgeted money,
  Actual money
)

insert into @T values
('NewSale',     1,      120,     45.23,     50.10),
('NewSale',     2,      30,      3.10,      1.2),
('NewSale',     3,      70,      45.00,     100.32)

select [Type], [1], [2], [3]
from
(
  select [Month],
         cast([Count] as money) as [Count],
         Budgeted,
         Actual
  from @T
) as T
unpivot
(
  Value for [Type] in ([Count], Budgeted, Actual)
) as U
pivot
(
  sum(Value) for [Month] in ([1], [2], [3])
) as P

Pruebatelo SE-Datos.

Respondido el 18 de enero de 21 a las 12:01

You need to do 3 selects and union the result to get a table that looks like that.

Por ejemplo:

  Select 'Count' as [Type], 120 AS 1, 40 AS 2, 70 AS 3
  UNION ALL
  Select 'Budgeted' as [Type], 45.23 AS 1, 3.10 AS 2, 45.00 AS 3
  UNION ALL
  Select 'Actual' as [Type], 50.1 AS 1, 1.2 AS 2, 100.32 AS 3

Will look like your example

So just replace each of those selects with a piviot that returns the row you want and you GTG

respondido 10 mar '12, 14:03

Thanks for your help. Just a quick question for dumb me...How can the SQL be Select 'Count' as [Type], 120 AS 1, 40 AS 2, 70 AS 3...I would not know the values at design time for Count, Budgeted, Actual etc...? - Cenizas a las cenizas

err.. Mikael was able to do it... I stand corrected. With my way you would use a standard pivot 3 different times for each place where my query has a select. Each of those select statements would give you just one row. - Hogan

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.