如何在一行上显示一对多的“多”

时间:2018-10-30 04:03:02

标签: sql-server database ms-access structure many-to-one

为我提供了2个文件,分别为两个表:“ VoterData”和“ VoterHistory”-完成预期显示的最佳方法是什么?

期望的显示

ID      | First Name | Last Name   | Election1 | Election2 | Election3
--------+------------+-------------+-----------+-----------+----------
2155077 | Camille    | Bocchicchio | 2016June7 | 2016Nov8  | 2018June5
2155079 | Manabu     | Lonny       | 2016June7 | 2016Nov8  | 
2155083 | Scott      | Bosomworth  | 2016June7 |           | 2018June5



一个-'VoterData'

lVoterUniqueID | szNameFirst | szNameLast
---------------+-------------+------------
2155077        | Camille     | Bocchicchio  
2155079        | Manabu      | Lonny  
2155083        | Scott       | Bosomworth  

很多-'VoterHistory'

lVoterUniqueID | sElectionAbbr 
---------------+---------------
2155077        | 2016June7     
2155077        | 2016Nov8      
2155077        | 2018June5  
2155079        | 2016June7      
2155079        | 2016Nov8      
2155083        | 2016June7       
2155083        | 2018June5    

1 个答案:

答案 0 :(得分:0)

使用交叉表查询

TRANSFORM First(H.sElectionAbbr) AS FirstOfsElectionAbbr
SELECT H.lVoterUniqueID AS ID, D.szNameFirst AS [First Name], D.szNameLast AS [Last Name]
FROM VoterData AS D INNER JOIN VoterHistory AS H ON D.lVoterUniqueID = H.lVoterUniqueID
GROUP BY H.lVoterUniqueID, D.szNameFirst, D.szNameLast
PIVOT H.sElectionAbbr;