在多对多表上将行转换为列

时间:2016-06-30 23:36:23

标签: sql sql-server tsql pivot left-join

所以我有三张桌子:

生:

StuConId   StuID   ConID  StuConType  Priority
----------------------------------------------
1          1       1      Parent      1
2          1       2      Guardian    2
3          2       3      Parent      1

StuCon:

ConID  ConName ConPhn
----------------------
1      John    5555555
2      Sally   4444444
3      Dana    3333333

联系人:

StuID  ConID1 StuConType1  ConName1  ConPhone1   ConID2 StuConType2  ConName2  ConPhone2
----------------------------------------------------------------------------------------
1      1      Parent        John     5555555     2      Guardian     Sally     4444444
2      3      Parent        Dana     3333333     Null   Null         Null      Null

我试图获得如下结果:

scanf()

到目前为止,我能做到这一点的唯一方法就是通过大量的左连接(一些学生最多有10个联系人,以便10个联盟为stucon加入,10个为联系人)

我非常确定这里可以应用一个支点,我只是无法弄清楚如何去做。

1 个答案:

答案 0 :(得分:2)

以下是动态执行此操作的一种方法:

DECLARE @selects VARCHAR(MAX) = '', @SQL VARCHAR(MAX) = '';
SELECT @selects += '
     , MAX(CASE WHEN SC.[Priority] = ' + CAST([Priority] AS VARCHAR(255)) + ' THEN C.ConID END) [ConID' + CAST([Priority] AS VARCHAR(255)) + ']
     , MAX(CASE WHEN SC.[Priority] = ' + CAST([Priority] AS VARCHAR(255)) + ' THEN SC.StuConType END) [StuConType' + CAST([Priority] AS VARCHAR(255)) + ']
     , MAX(CASE WHEN SC.[Priority] = ' + CAST([Priority] AS VARCHAR(255)) + ' THEN C.ConName END) [ConName' + CAST([Priority] AS VARCHAR(255)) + ']
     , MAX(CASE WHEN SC.[Priority] = ' + CAST([Priority] AS VARCHAR(255)) + ' THEN C.ConPhn END) [ConPhone' + CAST([Priority] AS VARCHAR(255)) + ']'
FROM StuCon
GROUP BY [Priority]
ORDER BY [Priority];

SET @SQL = 'SELECT StuID' + @selects + ' FROM StuCon SC LEFT JOIN Contacts C ON C.ConID = SC.ConID GROUP BY StuID;';
EXEC(@SQL);

注意:联系人可能应该是正常JOIN而不是LEFT JOIN,但这是左连接,以防表格之间存在一些不一致。 <{1}}表尚未加入,因为没有必要。