What wrong with this code (or my sanity for that matter 😀 ).
The Distinct clause in the Select statement is NOT working. It’s result set contains All rows for Each EmpID in ej. Please help!!
Declare @SurveyID int;
SET @SurveyID = 2;
IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t1
SELECT Distinct(ej.EmpID),
ej.JobCode,
ej.SurveyID,
ej.IsCompleted,
Coalesce(ej.Declined,0) AS Declined,
emp.Company,
emp.UserID,
emp.LoginRecord,
count(JobCode) AS Benchmark
into #t
FROM SAS.EmployerJobs ej
INNER JOIN SAS.Employer emp
ON ej.EmpID = emp.EmpID
Where (ej.SurveyID = @SurveyID)
GROUP BY ej.EmpID, ej.JobCode, ej.SurveyID, ej.IsCompleted, Declined, emp.Company, emp.UserID, emp.LoginRecord
Order by ej.EmpID ASC
Select * from #t
drop table #t
If you only require one row for each distinct EmpID in the result set, then you need to decide how to aggregate the multiple rows of data (multiple jobs) for each EmpID. For example, choosing the minimum value.
But from the names and relations, it seems that an EmpID can have multiple jobs, so it doesn’t seem to make sense to expect only one row per EmpID if you want also to list the individual jobs.
UPDATE: To count the number of JobCodes
Your original query attempted to pull in data that varies per job, and that is why you were not getting the aggregation. (E.g. IsCompleted, declined etc..) For aggregation to work, only include data that is an aggregate of the job data, like
count(JobCode), or doesn’t vary per job, such as employer attributes.