简体   繁体   中英

Remove Duplicates from SQL Query

I am using this query currently to trigger a customer event. But sometimes the same customer will be in the results because they are assigned a different WorkOrderId, which is my primary filter. So, I want to expand the filter to also look for a unique CustomerName. In other words, if the query returns two rows with the same CustomerName then I want it to exclude the 2nd row altogether.

SELECT CustomerName, JobId, Email, CCEmail, WorkOrderId AS id
FROM dbo.vwWorkOrderDetail
WHERE JobStatusId=3 AND Active=1 AND LocationStopTypeId=1
ORDER BY WorkOrderId DESC

I've tried using DISTINCT but I continue to get results that include the same CustomerName in different rows. How can I setup this query so it returns results that passed all of the WHERE conditions and then only shows rows with a unique CustomerName?

As long as you include WorkOrderId, DISTINCT will do nothing for you. DISTINCT can only eliminate duplicates where all of the columns specified in the SELECT contain the same information. So to use DISTINCT to eliminate duplicate customers, you would need to do this:

SELECT DISTINCT CustomerName, JobId, Email, CCEmail
FROM dbo.vwWorkOrderDetail
WHERE JobStatusId=3 AND Active=1 AND LocationStopTypeId=1
ORDER BY WorkOrderId DESC

The best way to approach this to preserve a WorkOrderId is to make a new view based on the underlying tables. You will need to decide what WorkOrderId of the available WorkOrderIds you want to present. Typically this is the highest ID. If all you need is the WorkOrderId itself and not the details, this is actually pretty simple. Note the code below is a naïve example that assumes CustomerId is tied directly to a work order. To really answer this properly you'd need to provide the code for vwWorkOrderDetail.

SELECT CustomerName, JobId, Email, CCEmail, (SELECT MAX(WorkOrderId) FROM WorkOrders WHERE CustomerID = Customers.CustomerID) AS WorkOrderID
FROM Customers
WHERE JobStatusId=3 AND Active=1 AND LocationStopTypeId=1
ORDER BY WorkOrderId DESC
SELECT CustomerName, JobId, Email, CCEmail, max(WorkOrderId) AS id
FROM dbo.vwWorkOrderDetail
WHERE JobStatusId=3 AND Active=1 AND LocationStopTypeId=1
GROUP BY CustomerName, JobId, Email, CCEmail

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM