我需要按如下方式调整表格: 初始表就像这样
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,不少也不多。
拜托,任何人都可以帮助我如何编写正确的查询?
答案 0 :(得分:0)
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服务器实例)。
答案 1 :(得分:0)
最新版本的SQL Server具有 PIVOT功能。
Here is an example如何在多个SQL Server版本中进行透视。
这个非常受欢迎的SO问题有许多好的答案:SQL Server PIVOT examples?
这是一个简单的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
答案 2 :(得分:0)
要对您的数据使用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