【发布时间】:2019-10-31 22:45:42
【问题描述】:
我正在尝试使用 Pivot 数据创建一个新表。
有人可以指出我正确的方向,或者帮助我进行查询以实现以下目标。
【问题讨论】:
-
你自己尝试过吗?这不是一个代码编写服务,如果您需要帮助,您已经尝试过并且需要指导来克服特定的绊脚石。您已经知道需要搜索的关键字 - 困难的部分是将其编写为动态查询。
标签: sql sql-server tsql pivot-table
我正在尝试使用 Pivot 数据创建一个新表。
有人可以指出我正确的方向,或者帮助我进行查询以实现以下目标。
【问题讨论】:
标签: sql sql-server tsql pivot-table
一种方法是结合 CTE 和带有分组的最终查询: 让我们首先在一个表中填充数据:
CREATE TABLE COMPUTERS (CUSTOMER_ID INT, COMPUTER_NAME VARCHAR(50), COMPUTER_OS VARCHAR(50));
INSERT INTO COMPUTERS VALUES (15001, 'DESKTOP-JKVB','Windows 7');
INSERT INTO COMPUTERS VALUES (15001, 'DESKTOP-SKVB','Windows 2012R2');
INSERT INTO COMPUTERS VALUES (15002, 'PC-JKVB45','Windows VISTA');
INSERT INTO COMPUTERS VALUES (15002, 'JOHN-PC','Windows 10');
INSERT INTO COMPUTERS VALUES (15002, 'SERVER-DC','Windows 7');
INSERT INTO COMPUTERS VALUES (15002, 'DATA-PC','Windows 2016');
INSERT INTO COMPUTERS VALUES (15002, 'PC-BACKOFFICE','Windows 2008R2');
INSERT INTO COMPUTERS VALUES (15003, 'DESKTOP-XPBACK','Windows 7');
INSERT INTO COMPUTERS VALUES (15003, 'PC-HDFU','Windows 2012R2');
INSERT INTO COMPUTERS VALUES (15003, 'DESKTOP-NO2','Windows 10');
INSERT INTO COMPUTERS VALUES (15004, 'SERVER-DHCP','Windows 7');
INSERT INTO COMPUTERS VALUES (15004, 'DESKTOP-NO1','Windows 2012R2');
这里是查询。唯一的方法是您必须知道用户拥有的最大记录数(这是 5 条记录)-dbfiddle:
;with cte as (
SELECT *,row_number() over (partition by Customer_ID order by Customer_ID) as Number
FROM computers
),
cte2 as (
select DISTINCT
c.Customer_ID,
c.Computer_Name,
'Computer_Name_' + cast(Number as varchar(1)) as Computer
from cte as c
),
cte_dist2 as (
select distinct
Customer_ID
from computers
),
cte3 as (
select c.Customer_ID,
c.Computer_OS,
'Computer_OS_' + cast(Number as varchar(1)) as OS
from cte as c
)
select DISTINCT
cd2.Customer_ID,
MAX(IIF(c2.Computer='Computer_Name_1',c2.Computer_Name,NULL)) as Computer_Name_1,
MAX(IIF(c3.OS='Computer_OS_1',c3.Computer_OS,NULL)) as Computer_OS_1,
MAX(IIF(c2.Computer='Computer_Name_2',c2.Computer_Name,NULL)) as Computer_Name_2,
MAX(IIF(c3.OS='Computer_OS_2',c3.Computer_OS,NULL)) as Computer_OS_2,
MAX(IIF(c2.Computer='Computer_Name_3',c2.Computer_Name,NULL)) as Computer_Name_3,
MAX(IIF(c3.OS='Computer_OS_3',c3.Computer_OS,NULL)) as Computer_OS_3,
MAX(IIF(c2.Computer='Computer_Name_4',c2.Computer_Name,NULL)) as Computer_Name_4,
MAX(IIF(c3.OS='Computer_OS_4',c3.Computer_OS,NULL)) as Computer_OS_4,
MAX(IIF(c2.Computer='Computer_Name_5',c2.Computer_Name,NULL)) as Computer_Name_5,
MAX(IIF(c3.OS='Computer_OS_5',c3.Computer_OS,NULL)) as Computer_OS_5
from cte_dist2 as cd2
inner join cte2 as c2 ON cd2.Customer_ID = c2.Customer_ID
inner join cte3 as c3 ON cd2.Customer_ID = c3.Customer_ID
group by cd2.Customer_ID
【讨论】: