Question : SQL DISTINCT Problem

I have 2 tables, a projects table and a ProjectsInfo table.  There may or may not be a ProjectsInfo record for every record in the Projects table.  I want to see all of the projects that belong to me and if there are associated records in the ProjectInfo, I want to see those records.  The distinct is not raising any errors, it just isn't working.  I only want to see 1 record for each project.  If that project has an associated ProjectInfo record, I want to see that one.

I also tried a Group By, but I wasn't sure how to group by just Projects.ID when I need all those other columns.  

Here is the SQL:
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
SELECT Distinct Projects.ID, ProjectInfo.ID AS _IDx, 
Projects._ReadOnly, Projects._UserGroupID, Projects._OrganizationID,  
Projects.[Project Name], ProjectInfo.[Job Number], ProjectInfo.[Description], 
ProjectInfo.[Project Manager] FROM Projects 
LEFT OUTER JOIN ProjectInfo on Projects.ID = ProjectInfo.ID 
AND ProjectInfo._UserGroupID = '1ee8022b-1fe4-4bce-9a80-c9ba672737b2' 
WHERE _Active = 1 ORDER BY Projects.[Project Name];

Answer : SQL DISTINCT Problem

If there is, then you will need to decide which of the projectinfo records to show like say the latest (e.g., higher [Job Number] equals later project info).

SELECT p.ID, i.ID AS _IDx, p._ReadOnly, p._UserGroupID, p._OrganizationID
, p.[Project Name], i.[Job Number], i.[Description], i.[Project Manager]
FROM Projects p
LEFT OUTER JOIN (
  SELECT *
  , ROW_NUMBER() OVER(PARTITION BY ID, _UserGroupID ORDER BY [Job Number] DESC) rn
   FROM ProjectInfo
) i on p.ID = i.ID
  AND i._UserGroupID = '1ee8022b-1fe4-4bce-9a80-c9ba672737b2'
  AND i.rn = 1
WHERE p._Active = 1
ORDER BY [Project Name];

Best regards,

Kevin

Random Solutions  
 
programming4us programming4us