来自JOIN表的PIVOT

时间:2017-03-30 02:08:43

标签: sql join pivot case

我有一个大型数据库,在这个数据库中,有两个表需要从中提取信息。我通过使用JOIN和CASE WHEN从两个表中提取了我需要的所有数据。这是输出屏幕截图

SQL Server output

这是我用来提取数据的代码:

SELECT [PORTMultiMax].[dbo].cardholdertable.cardid as CardID,CardHolderTable.FirstName as FirstName,CardHolderTable.LastName as LastName, CardHolderTable.InitLet as MI, CardHolderPersonalDataXrTable.PersonalDataItem as Data,
  CASE WHEN PersonalDataID = '4' THEN 'SSN'
         WHEN PersonalDataID = '22' THEN 'Employer'
         WHEN PersonalDataID = '30' THEN 'Training Type'
         WHEN PersonalDataID = '32' THEN 'Primary Sponsor'
         WHEN PersonalDataID = '37' THEN 'Training Date'
         ELSE NULL END AS Description
  FROM [PORTMultiMax].[dbo].[CardHolderTable]
  join [PORTMultiMax].[dbo].[CardHolderPersonalDataXrTable]
  on cardholdertable.CardID=CardHolderPersonalDataXrTable.CardID
    where PersonalDataID IN (4,22,30,32,33,37)
    order by LastName

所涉及的表名为:CardHolderTable和CardHolderPersonalDataXrTable 我接下来需要做的是摆脱数据中的重复名称条目。例如,“JAMES AARON”有多行,因为他有多个描述符(“Training Date,TrainingType,Employer,and SSN”)。

我想尝试使用PIVOT将行数据拉出来并将它们放在名为“SSN,Employer等......”的列中。我的问题是我之前从未使用过PIVOT,而且我对如何将PIVOT代码应用于当前的SQL查询感到困惑。

请帮助。非常感谢你

1 个答案:

答案 0 :(得分:0)

鉴于您的查询,我认为条件聚合更简单:

SELECT ch.FirstName, ch.LastName
       MAX(CASE WHEN PersonalDataID = '4' THEN 1 ELSE 0 END) as is_SSN
       MAX(CASE WHEN PersonalDataID = '22' THEN ELSE 0 END) as is_Employer,
       MAX(CASE WHEN PersonalDataID = '30' THEN ELSE 0 END) as is_TrainingType,
       MAX(CASE WHEN PersonalDataID = '32' THEN ELSE 0 END) as is_PrimarySponsor,
       MAX(CASE WHEN PersonalDataID = '37' THEN ELSE 0 END) as is_TrainingDate
from [PORTMultiMax].[dbo].[CardHolderTable] ch join
     [PORTMultiMax].[dbo].[CardHolderPersonalDataXrTable] cp
     on ch.CardID = cp.CardID
where PersonalDataID IN (4, 22, 30, 32, 33, 37)
group by ch.FirstName, ch.LastName;