查找具有单个公共字段的记录,但其他字段的值不同

时间:2014-01-14 20:53:23

标签: sql sql-server

我在SQL Server中有一个具有此结构的表:

Promotions
======
id
promoId
customerId
dealPeriod
lob

我需要找到记录的promoId相同的记录组,但customerId,dealPeriod或lob是不同的。

所以,我对退回此事不感兴趣:

id    promoId     customerId    dealPeriod    lob
1     p00100            100           2013    PL
2     p00100            100           2013    PL
3     p00100            100           2013    PL

但是我希望以不同的值返回这个组:

id    promoId     customerId    dealPeriod    lob
1     p00101            100           2013    PL
2     p00101            100           2013    PL
3     p00101            100           2013    RT

或者这个具有不同客户ID的组:

id    promoId     customerId    dealPeriod    lob
1     p00102            100           2013    PL
2     p00102            200           2013    PL
3     p00102            100           2013    PL

或者这个具有不同交易期的组:

id    promoId     customerId    dealPeriod    lob
1     p00103            100           2013    PL
2     p00103            200           2014    PL
3     p00103            100           2013    PL

以下是我的尝试:

SELECT t1.id, t1.customerId, t1.promoId, t1.dealPeriod, t1.lob
FROM promotion t1
INNER JOIN promotion t2 ON t1.promoid = t2.promoid
WHERE (t1.customernumber <> t2.customernumber) 
OR (t1.dealPeriod <> t2.dealPeriod) 
OR (t1.lob <> t2.lob)

这会返回包含我不想要的记录:

id    promoId     customerId    dealPeriod    lob
1     p00100            100           2013    PL
2     p00100            100           2013    PL
3     p00100            100           2013    PL
4     p00101            102           2013    RT
5     p00101            102           2013    RT
6     p00101            102           2013    RT

2 个答案:

答案 0 :(得分:0)

试试这个

SELECT DISTINCT p.*
FROM Promotions p 
    JOIN Promotions q ON p.promoid = q.promoid AND p.id <> q.id
WHERE (p.customerId <> q.customerId) 
    OR (p.dealPeriod <> q.dealPeriod) 
    OR (p.lob <> q.lob)

答案 1 :(得分:0)

;With CTE
AS
 (
  SELECT * , RN = ROW_NUMBER() OVER (PARTITION BY promoId ORDER BY promoId)
  FROM Promotions
 )
SELECT * 
FROM CTE