I am selecting job numbers and information from a table and want to include names of the primary and secondary consultants assigned to that job. The information isn't stored in the table as a column for primary and secondary, however. Rather, it is stored using numerical values which correspond to the consultant's relationship to that job, where 9 is primary consultant and 10 is the secondary. For example:
Job # UserRelationship UserId
1 9 Joe Bloggs
1 10 Mickey Mouse
2 9 Goofy
2 10 Alan Sugar
As such I am using
max(case when UserRelationship=9 then userid else null end) as [primary consultant],
max(case when UserRelationship=10 then userid else null end) as [secondary consultant]
To create the result set with both consultants on the same line.
I am trying to integrate this into a larger query, which counts the amount of hours worked on the job. The above solution seems to be doubling the amount of hours worked when both the primary and secondary consultant are present (in the very few occasions where there is only one consultant this isn't happening).
I can see that it will have something to do with counting the number of hours worked twice because of the two UserRelationshipId rows. Is there a way to recify this?
Below is my full query so hopefully the problem is evident:
WHEN dbo.Placements.SectorId=51 THEN 'Gov/Corp'
WHEN dbo.Placements.SectorId=55 THEN 'Gov/Corp'
WHEN dbo.Placements.SectorId=56 THEN 'Gov/Corp'
END AS 'Sector',
ISNULL (SUM(dbo.TimesheetHours.HoursWorked),'0') AS 'Hours Worked' ,
max(case when dbo.PlacementConsultants.UserRelationshipId=9 then dbo.Users.Username+ ' ' +dbo.Users.Surname else null end) as [primary consultant],
max(case when dbo.PlacementConsultants.UserRelationshipId=10 then dbo.Users.Username+ ' ' +dbo.Users.Surname else null end) as [secondary consultant],