Sql – MS Access SQL Duplicate Rows

ms-accessreportsql

Query:

SELECT DISTINCT ([Equipment List].ID) AS Expr1, [Job Assignments].Job
FROM [Equipment List] LEFT JOIN [Job Assignments] 
    ON [Equipment List].ID = [Job Assignments].EquipmentID;

In this query, the equipment ID is distinct if and only if I do not add the [Job Assignments].Job in the select statement. As soon as I do, I get many duplicates. The Job Assignments table has many jobs, but I am only interested in the one with the [Date Returned] blank or null. Any ideas how to accomplish this? I am using this as a report, so It gives me an error when I try to use inner sql queries. Also this is a simplified query, as the original has multiple selects. What am I doing wrong? Any help would be greatly appreciated.

Update: I am looking to select only one row from [Job Assignments] Table. Any ideas?

Best Solution

DISTINCT returns distinct combinations of all columns in the SELECT statement, which is why introducing a second column also introduces dupes.

It sounds like you can get away with a WHERE clause:

SELECT DISTINCT ([Equipment List].ID) AS Expr1, [Job Assignments].Job 
FROM [Equipment List] 
LEFT JOIN [Job Assignments] ON [Equipment List].ID = [Job Assignments].EquipmentID
WHERE [Job Assignments].[Date Returned] IS NULL

You can't have a "blank" date, so if you're seeing blanks then chances are you're not using a datetime type to store your date - in this case, you'll need to say:

WHERE COALESCE([Job Assignments].[Date Returned], '') = ''

Edit: Latest solution based on comments below:

;WITH LatestJobs
AS
(SELECT     ja.EquipmentID, ja.Job,
            ROW_NUMBER() OVER ( PARTITION BY EquipmentID 
                                ORDER BY [Date Returned] DESC) AS RowNumber
FROM        [Job Assignments] AS ja)

SELECT      el.ID AS EquipmentID, 
            lj.Job
FROM        [Equipment List] AS el
LEFT JOIN   LatestJobs AS lj ON el.ID = lj.EquipmentID
            AND lj.RowNumber = 1