我有这张桌子
CREATE TABLE COMPUTERS
(
CUSTOMER_ID INT,
COMPUTER_NAME VARCHAR(50),
COMPUTER_OS VARCHAR(50)
);
INSERT INTO COMPUTERS
VALUES (15001, 'DESKTOP-JKVB','Windows 7'),
(15001, 'DESKTOP-SKVB','Windows 2012R2'),
(15002, 'PC-JKVB45','Windows VISTA'),
(15002, 'JOHN-PC','Windows 10'),
(15002, 'SERVER-DC','Windows 7'),
(15002, 'DATA-PC','Windows 2016'),
(15002, 'PC-BACKOFFICE','Windows 2008R2'),
(15003, 'DESKTOP-XPBACK','Windows 7'),
(15003, 'PC-HDFU','Windows 2012R2'),
(15003, 'DESKTOP-NO2','Windows 10'),
(15004, 'SERVER-DHCP','Windows 7'),
(15004, 'DESKTOP-NO1','Windows 2012R2');
借助于堆栈溢出,我编写了一个查询以旋转上述数据。 我的问题是我们可以使用数据透视表数据的结果创建临时表还是普通表。
PIVOT查询
;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(100)) 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(100)) 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
答案 0 :(得分:2)
是的,您可以在下面使用临时表,其中显示了两种可用于创建临时表的方法
select * into #temp from (--select query of the final cte function
or query)
和临时表将自动为您创建。
如果要创建自己的临时表,请如下创建临时表。
例如
create table #Temp
(
EventID int,
EventTitle Varchar(50),
EventStartDate DateTime,
EventEndDate DatetIme,
EventEnumDays int,
EventStartTime Datetime,
EventEndTime DateTime,
EventRecurring Bit,
EventType int
)
并使用Insert Into #Temp --select query of the final cte function
or query
也会对您有用。