简体   繁体   English

从SQL查询中删除重复项

[英]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. 但是有时结果中会出现同一位客户,因为他们被分配了一个不同的WorkOrderId,这是我的主要过滤条件。 So, I want to expand the filter to also look for a unique CustomerName. 因此,我想扩展过滤器以查找唯一的CustomerName。 In other words, if the query returns two rows with the same CustomerName then I want it to exclude the 2nd row altogether. 换句话说,如果查询返回具有相同CustomerName的两行,那么我希望它完全排除第二行。

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. 我尝试使用DISTINCT,但我继续获得在不同行中包含相同CustomerName的结果。 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? 如何设置此查询,使其返回通过所有WHERE条件的结果,然后仅显示具有唯一CustomerName的行?

As long as you include WorkOrderId, DISTINCT will do nothing for you. 只要您包括WorkOrderId,DISTINCT都不会为您做任何事情。 DISTINCT can only eliminate duplicates where all of the columns specified in the SELECT contain the same information. DISTINCT只能消除SELECT中指定的所有列都包含相同信息的重复项。 So to use DISTINCT to eliminate duplicate customers, you would need to do this: 因此,要使用DISTINCT消除重复的客户,您需要这样做:

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. 保留WorkOrderId的最佳方法是根据基础表创建一个新视图。 You will need to decide what WorkOrderId of the available WorkOrderIds you want to present. 您将需要确定要显示的可用WorkOrderId中的哪个WorkOrderId。 Typically this is the highest ID. 通常,这是最高的ID。 If all you need is the WorkOrderId itself and not the details, this is actually pretty simple. 如果您只需要WorkOrderId本身而不是细节,这实际上很简单。 Note the code below is a naïve example that assumes CustomerId is tied directly to a work order. 请注意,下面的代码是一个简单的示例,它假定CustomerId直接绑定到工作订单。 To really answer this properly you'd need to provide the code for vwWorkOrderDetail. 要真正正确回答此问题,您需要提供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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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