简体   繁体   中英

Inserting Multiple Records on One Data Row SQL

I am trying to get multiple employee dependents to be on the same row of data on my output file. I can get one dependent on the employee's row, but not more than one.

I tried using a Left Join where I am joining the AutoNum so it matches with employees and dependents, but I still am only pulling one dependent.

Any ideas on how to get all needed data on one row in a SQL Access query?

 SELECT E.FirstName, E.LastName, E.SSN, 
 Switch(E.MemberStartDate<="2018-01-01" And E.MemberEndDate>="2018-12-31","X") AS Cov12Months, 
 D.DepFirstName, D.DepLastName, D.ResponsibleIndividualSSN,     D.CoveredIndividualSSN, D.DepDOB, 
 Switch(D.DepStartDate<="2018-01-01" And D.DepEndDate>="2018-12-31","X") AS DCov12Months, 
 FROM EMP_Test AS E LEFT JOIN Dep_Test AS D ON E.AutoNum = D.AutoNum;

Below is a sample image of what my results are currently. As you can see, Charles Soper's record is correct since he only has one dependent. But Susan Smith has two records because she has two dependents. I need both dependents on one row 在此处输入图片说明

A VBA method is one approach and examples provided in comment link. A CROSSTAB is also a possibility. Each approach has its pros and cons.

Consider:

TRANSFORM Max([DepFirstName] & " " & [DepLastName]) AS DepName
SELECT EmpDeps.EmpID
FROM EmpDeps
GROUP BY EmpDeps.EmpID
PIVOT DCount("*","EmpDeps","EmpID='" & [EmpID] & "' AND ID<" & [ID])+1 In (1,2,3,4,5,6,7,8,9,10);

This requires a unique identifier field in table - autonumber should serve. Defining column names in PIVOT clause allows query to be stable enough to use as report RecordSource. This query can be joined to Employees table to retrieve additional employee info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM