• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 312
  • Last Modified:

DISTINCT Row in a CTE

I have a CTE trying to select only distinct Contacts that are related to a contact in tProject. But it will repeat the contact for every project they are in. Can someone please help get the contact only once please.
With ContactCTE (ID, sFirstName, sLastName, sBusinessName, sPhone, sMobile, sEmail, sStreet, sStreetNo, IsBuilder, SuburbID)
AS (
SELECT Distinct ID, sFirstName, sLastName, sBusinessName, sPhone, sMobile, sEmail, sStreet, sStreetNo, IsBuilder, SuburbID
FROM tContacts
)
SELECT    ContactCTE.ID,  ContactCTE.sFirstName + ' ' + ContactCTE.sLastName AS sName, ContactCTE.sBusinessName, ContactCTE.sPhone, ContactCTE.sMobile, ContactCTE.sEmail,
                         Isnull(tSuburbs.sSuburb, '') as sSuburb, ISNULL(tSuburbs.sPostcode, '') as sPostcode, ContactCTE.sStreetNo + ' ' + ContactCTE.sStreet AS sAddress, ContactCTE.IsBuilder,
                         ContactCTE.ID
FROM            ContactCTE INNER JOIN
                         tProject ON ContactCTE.ID = tProject.AgentID LEFT OUTER JOIN
                         tSuburbs ON ContactCTE.SuburbID = tSuburbs.ID
                         WHERE ContactCTE.IsBuilder = 1

Open in new window

0
mgordon-spi
Asked:
mgordon-spi
1 Solution
 
Kevin CrossChief Technology OfficerCommented:
Hi.

It does not appear you are using tProject in the SELECT at all. Is it's function just to ensure that the contact has at least one project?

If so, then I would try something like this (I removed all the parts that are not changing):
With ContactCTE (/*...*/)
AS (
/*...*/
)
SELECT /*...*/
FROM ContactCTE
LEFT OUTER JOIN tSuburbs ON ContactCTE.SuburbID = tSuburbs.ID
WHERE ContactCTE.IsBuilder = 1
AND EXISTS (
    SELECT 1
    FROM tProject
    WHERE ContactCTE.ID = tProject.AgentID
)
;


Hope that helps!
0
 
mgordon-spiAuthor Commented:
That was my first CTE and confused me completely. But that seemed to do the trick, thank you.
0

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now