在返回不同行的查询中选择NON-DISTINCT列

时间:2014-08-13 12:31:48

标签: sql sql-server tsql

以下查询返回我需要的结果,但我必须添加行的ID然后更新它。如果我直接在select语句中添加ID,那么我将返回更多结果,因为每个ID都是唯一的,因此DISTINCT语句将该行视为唯一。

SELECT DISTINCT ucpse.MemberID, ucpse.ProductID, ucpse.UserID
FROM UserCustomerProductSalaryExceptions as ucpse
WHERE EXISTS (SELECT NULL 
            FROM UserCustomerProductSalaryExceptions as upcse2 
            WHERE ucpse.userid = upcse2.userid AND ucpse.MemberID = upcse2.MemberID AND ucpse.ProductID = upcse2.ProductID
            GROUP BY upcse2.UserID, upcse2.memberid, upcse2.productid 
            HAVING COUNT(UserID) >= 2
            )

所以基本上我需要在Select语句中添加ucpse.ID,同时保留MemberID,ProductID和UserID的DISTINCT值。

任何想法?

谢谢

4 个答案:

答案 0 :(得分:3)

据你评论: 如果对于具有给定产品和给定客户的给定员工,数据已被复制67次,我只需要保留其中一个记录。它不重要哪一个,所以这就是我使用DISTINC获得给定员工与给定产品和给定客户的独特组合的原因。

您可以使用MIN()MAX()GROUP BY代替DISTINCT

SELECT MAX(ucpse.ID) AS ID, ucpse.MemberID, ucpse.ProductID, ucpse.UserID
FROM UserCustomerProductSalaryExceptions as ucpse
WHERE EXISTS (SELECT NULL 
            FROM UserCustomerProductSalaryExceptions as upcse2 
            WHERE ucpse.userid = upcse2.userid AND ucpse.MemberID = upcse2.MemberID AND ucpse.ProductID = upcse2.ProductID
            GROUP BY upcse2.UserID, upcse2.memberid, upcse2.productid 
            HAVING COUNT(UserID) >= 2
            )

GROUP BY ucpse.MemberID, ucpse.ProductID, ucpse.UserID

<强>更新

从您的评论我认为以下查询是您需要的

DELETE FROM  UserCustomerProductSalaryExceptions
WHERE ID NOT IN  ( SELECT MAX(ucpse.ID) AS ID
                         FROM #UserCustomerProductSalaryExceptions
                         GROUP BY ucpse.MemberID, ucpse.ProductID, ucpse.UserID
                         HAVING COUNT(ucpse.ID) >= 2
                     )

答案 1 :(得分:1)

如果您只想删除重复项,则可以执行此操作:

WITH X AS
(SELECT ID,
ROW_NUMBER() OVER (PARTITION BY MemberID, ProductID, UserID ORDER BY ID) AS DupRowNum<br
FROM UserCustomerProductSalaryExceptions
)
DELETE X WHERE DupRowNum > 1

答案 2 :(得分:0)

ID不是必需的 - 尝试:

UPDATE uu SET
    <your settings here>
FROM UserCustomerProductSalaryExceptions uu
    JOIN ( <paste your entire query above here> 
         ) uc ON uc.MemberID=uu.MemberId AND uc.ProductID=uu.ProductId AND uc.UserID=uu.UserId

答案 3 :(得分:0)

从你的数据结构的声音(我强烈建议尽快正常化),听起来你应该更新所有记录。听起来好像每个副本都很重要,因为它包含一些关于员工与客户或产品的关系的信息。

我可能会更新所有记录。试试这个:

UPDATE UCPSE 
SET
    --Do your updates here
FROM UserCustomerProductSalaryExceptions as ucpse
JOIN
(
    SELECT UserID, MemberID, ProductID
    FROM UserCustomerProductSalaryExceptions
    GROUP BY UserID, MemberID, ProductID
    HAVING COUNT(UserID) >= 2
) T
ON ucpse.UserID = T.UserID AND ucpse.MemberID = T.MemberID AND ucpse.ProductID = T.ProductID