我该如何转动呢

时间:2014-05-25 23:37:48

标签: sql sql-server pivot

我正在尝试调整一些信息而无法解决它。请帮我。我正在使用SQL Express 2012。 我写了这个例子:

CREATE TABLE #temp
(
    Mes varchar(2),
    Qty int,
    Modelo varchar(50)
)
insert into #temp values('01', 11, 'TC')
insert into #temp values('01', 21, 'TC2')
insert into #temp values('01', 22, 'Plus2')
insert into #temp values('02', 12, 'TC')
insert into #temp values('02', 22, 'TC2')
insert into #temp values('02', 32, 'Plus2')
insert into #temp values('03', 13, 'TC')
insert into #temp values('03', 23, 'TC2')
insert into #temp values('03', 33, 'Plus2')

SELECT Modelo, [AAA] as Mes1, [BBB] as Mes2, [CCC] as Mes3
from 
(
    select Mes, Modelo, Qty
    from #temp
) x
PIVOT
(
   SUM(Qty)
   FOR Mes IN([AAA], [BBB], [CCC])
) as p

drop table #temp

结果是:

 Modelo | Mes1  |  Mes2  |  Mes3
-------------------------------
 Plus2  | NULL  |  NULL  |  NULL
 TC     | NULL  |  NULL  |  NULL
 TC2    | NULL  |  NULL  |  NULL

我这里有2个问题,第一个没有导致交集模型(行中的Modelo)和列(aaa,bbb,ccc)中的月(Mes)

第二个是如何直接将月份(Mes)名称放在列中而不使用Mes1等。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您在Mes列中插入了(' 01',' 02',' 03')。价值观如AAA',' BBB'和CCC'是无效值,将返回null。 因此,您必须按照以下方式更改代码:

CREATE TABLE #temp
(
    Mes varchar(2),
    Qty int,
    Modelo varchar(50)
)
insert into #temp values('01', 11, 'TC')
insert into #temp values('01', 21, 'TC2')
insert into #temp values('01', 22, 'Plus2')
insert into #temp values('02', 12, 'TC')
insert into #temp values('02', 22, 'TC2')
insert into #temp values('02', 32, 'Plus2')
insert into #temp values('03', 13, 'TC')
insert into #temp values('03', 23, 'TC2')
insert into #temp values('03', 33, 'Plus2')

SELECT Modelo, [01] as Mes1, [02] as Mes2, [03] as Mes3
from 
(
    select Mes, Modelo, Qty
    from #temp
) x
PIVOT
(
   SUM(Qty)
   FOR Mes IN([01], [02], [03])
) as p
drop table #temp

它将返回:

Modelo  | Mes1  | Mes2  | Mes3
--------+-------+-------+-----------
Plus2   | 22    | 32    | 33
TC      | 11    | 12    | 13
TC2     | 21    | 22    | 23

答案 1 :(得分:0)

如果你在谈论一年中的12个月,你可以这样做:

SELECT 
T1.Modelo
,   MAX(CASE WHEN T1.Mes = '01' THEN T1.Qty ELSE NULL END)      AS [JAN]
,   MAX(CASE WHEN T1.Mes = '02' THEN T1.Qty ELSE NULL END)      AS [FEB]
,   MAX(CASE WHEN T1.Mes = '03' THEN T1.Qty ELSE NULL END)      AS [MAR]
,   MAX(CASE WHEN T1.Mes = '04' THEN T1.Qty ELSE NULL END)      AS [APR]
,   MAX(CASE WHEN T1.Mes = '05' THEN T1.Qty ELSE NULL END)      AS [MAY]
,   MAX(CASE WHEN T1.Mes = '06' THEN T1.Qty ELSE NULL END)      AS [JUN]
,   MAX(CASE WHEN T1.Mes = '07' THEN T1.Qty ELSE NULL END)      AS [JUL]
,   MAX(CASE WHEN T1.Mes = '08' THEN T1.Qty ELSE NULL END)      AS [AGO]
,   MAX(CASE WHEN T1.Mes = '09' THEN T1.Qty ELSE NULL END)      AS [SEP]
,   MAX(CASE WHEN T1.Mes = '10' THEN T1.Qty ELSE NULL END)      AS [OCT]
,   MAX(CASE WHEN T1.Mes = '11' THEN T1.Qty ELSE NULL END)      AS [NOV]
,   MAX(CASE WHEN T1.Mes = '12' THEN T1.Qty ELSE NULL END)      AS [DEC]
FROM #temp T1
GROUP BY T1.Modelo

参见工作例:SQL Fiddle