SQL连接表pivot不带聚合

时间:2015-09-01 09:23:01

标签: sql-server

我有两张桌子:

Table1
ID  TYPE
1   ABC1
2   ABC2
3   ABC3

Table2
ID  Data
1   100
1   101
2   10
2   90

我希望结果看起来像这样:

ID  Data1  Data2
1   100    101
2   10     90

但是我在制作枢轴方面的尝试总是很重要。到目前为止,我有:

With Inital_Data As ( 
Select 
A.ID,
B.Data As Data1,
B.Data As Data2

From 
Table1 A join
Table2 B on
A.ID = B.ID
) 

Select * 
From
 Initial_Data
 PIVOT
(Max(ID) FOR Data IN (Data1,Data2)) p

我知道这是垃圾,但到目前为止,即使是我想要实现的逻辑也逃避了我,更不用说语法了!谁能给我一个指导手?

1 个答案:

答案 0 :(得分:0)

有多个列的透视需要一些技巧,我更喜欢XML连接。首先,我只在一个XML中获取每个ID的所有值,然后您可以逐个获取这些值:

只需将其粘贴到空查询窗口并执行即可。适应您的需求

编辑:包括来自TABLE1的列类型作为ID的标题...

DECLARE @Table1 TABLE(ID INT,[TYPE] VARCHAR(10));
INSERT INTO @Table1 VALUES
 (1,'ABC1')
,(2,'ABC2')
,(3,'ABC3');

DECLARE @Table2 TABLE(ID INT,DATA INT);
INSERT INTO @Table2 VALUES
 (1,100)
,(1,101)
,(2,10)
,(2,90);

WITH DistinctIDs AS
(
    SELECT DISTINCT tbl2.ID,tbl1.[TYPE] 
    FROM @Table2 AS tbl2
    INNER JOIN @Table1 AS tbl1 ON tbl1.ID=tbl2.ID
)
SELECT ID,[TYPE]
      ,concatXML.x.value('/root[1]/item[1]/@data','int') AS Data1
      ,concatXML.x.value('/root[1]/item[2]/@data','int') AS Data2
FROM DistinctIDs AS dIDs
CROSS APPLY
(
    SELECT ID AS [@id],DATA AS [@data]
    FROM @Table2 AS tbl WHERE tbl.ID=dIDs.ID
    FOR XML PATH('item'), ROOT('root'),TYPE
) AS concatXML(x)