我需要按如下方式透视一个表:初始表格就像这个
GEO PRD PACK DATATYPE Sales1 Sales2
T1 P1 M1 22 1 2
T1 P1 M1 23 2 8
T1 P1 M1 24 3 5
T2 P2 M2 22 3 2
T2 P2 M2 23 1 4
T2 P2 M2 24 1 7
我想要的是:
GEO PRD PACK 22_Sales1 22_Sales2 23_Sales1 23_Sales2 24_Sales1 24_Sales2
T1 P1 M1 1 2 2 8 3 5
T2 P2 M2 3 2 1 4 1 7
这里,不同的DATATYPE是固定的:永远是:22,23,24,不少于也不多于。
有人能帮我写正确的查询吗?
select geo, prd, pack,
sum(sales_22_1) sales_22_1,
sum(sales_22_2) sales_22_2,
sum(sales_23_1) sales_23_1,
sum(sales_23_2) sales_23_2,
sum(sales_24_1) sales_24_1,
sum(sales_24_2) sales_24_2
from
(select geo, prd, pack,
(case when datatype = 22 then sales1
else null
end) as sales_22_1,
(case when datatype = 22 then sales2
else null
end) as sales_22_2,
(case when datatype = 23 then sales1
else null
end) as sales_23_1,
(case when datatype = 23 then sales2
else null
end) as sales_23_2,
(case when datatype = 24 then sales1
else null
end) as sales_24_1,
(case when datatype = 24 then sales2
else null
end) as sales_24_2
from mytab)
group by geo, prd, pack
(未经测试,因为我没有可用的SQL server实例)。
SQL Server的最新版本具有PIVOT函数。
以下是如何在几个SQL Server版本中进行数据透视的示例。
对于这个非常流行的SO问题,有很多很好的答案:SQL Server PIVOT示例?
下面是一个简单PIVOT语句的示例:
SELECT act AS 'Action', [View] as 'View', [Edit] as 'Edit'
FROM (
SELECT act, cmd FROM data
) AS src
PIVOT (
MAX(cmd) FOR cmd IN ([View], [Edit])
) AS pvt
要在数据中使用PIVOT
,您需要使用以下内容。这首先执行UNPIVOT
,然后执行PIVOT
,以获得所需格式的数据:
create table t1
(
geo varchar(2),
prd varchar(2),
pack varchar(2),
datatype int,
sales1 int,
sales2 int
)
insert into t1 values ('T1', 'P1', 'M1', 22, 1, 2)
insert into t1 values ('T1', 'P1', 'M1', 23, 2, 8)
insert into t1 values ('T1', 'P1', 'M1', 24, 3, 5)
insert into t1 values ('T2', 'P2', 'M2', 22, 3, 2)
insert into t1 values ('T2', 'P2', 'M2', 23, 1, 4)
insert into t1 values ('T2', 'P2', 'M2', 24, 1, 7)
select *
from
(
select geo, prd, pack, cast(datatype as varchar(5)) + '_' + col col,value
from t1
unpivot
(
value
for col in (sales1, sales2)
) u
) x
pivot
(
sum(value)
for col in ([22_sales1], [22_sales2], [23_Sales1], [23_Sales2], [24_Sales1], [24_Sales2])
) p
请参阅带有演示的SQL Fiddle