Using SQL Server, I have multiple tables:
Assignments
aID,
acID,
clientID,
userID,
pos,
dateOn
AssignmentCarriers
acID,
clientID,
cName,
isAssignment
Users
userID,
fName
Clients
clientID,
cName,
code
Each client has multiple carriers. Each carrier has 3 positions to be filled (the assignment).
I wrote a query that returns the proper information, but instead of returning the assignment on one line with the 3 different positions (for each carrier that assignment has), it returns a line for each position and user.
Here's my query:
SELECT DISTINCT
c.code,
c.cName,
ac.cName,
(SELECT fname
FROM assignments
INNER JOIN users ON users.userID = assignments.userID
WHERE pos = 1 AND aID = a.aID) AS [User 1],
(SELECT dateOn
FROM assignments
WHERE pos = 1 AND aID = a.aID) AS [Date Assigned 1],
(SELECT fname
FROM assignments
INNER JOIN users ON users.userID = assignments.userID
WHERE pos = 2 AND aID = a.aID) AS [User 2],
(SELECT dateOn
FROM assignments
WHERE pos = 2 AND aID = a.aID) AS [Date Assigned 2],
(SELECT fname
FROM assignments
INNER JOIN users ON users.userID = assignments.userID
WHERE pos = 3 AND aID = a.aID) AS [User 3],
(SELECT dateOn
FROM assignments
WHERE pos = 3 AND aID = a.aID) AS [Date Assigned 3]
FROM
clients c
INNER JOIN
assignments a ON a.clientID = c.clientID
INNER JOIN
assignmentCarriers ac ON ac.acID = a.acID
WHERE
isAssignment = 'True'
AND c.active = 'True'
ORDER BY
c.cName
This returns:
HDPT Home Depot R+L Domestic Phil Brown 4/1/2023 Null Null Null Null
HDPT Home Depot R+L INTL Phil Brown 5/12/2000 Null Null Null Null
HDPT Home Depot R+L Domestic Null Null Mark Twain 1/22/15 Null Null
HDPT Home Depot R+L INTL Null Null Jen Gump 11/12/12 Null Null
HDPT Home Depot R+L Domestic Null Null Null Null Rob Mills 2/2/12
HDPT Home Depot R+L INTL Null Null Null Null John Smith 12/2/22
The desired output should be something like:
HDPT Home Depot R+L Domestic Phil Brown 4/1/2023 Mark Twain 1/22/15 Rob Mills 2/2/12
HDPT Home Depot R+L INTL Phil Brown 5/12/2000 Jen Gump 11/12/12 John Smith 12/2/22
How do I accomplish this?
Pretty sure that conditional aggregation is what you are after here. Also, I greatly simplified all those subqueries into case expressions. This should produce what you are looking for.