获取一列相同但另一列不同的记录

时间:2016-01-27 08:55:26

标签: sql-server

我试图比较两个"列表"在同一个表中获取记录,其中customerId列具有相同的值但storeid不同。

列表(表格定义)

name             listid   storeid   customerid

ComparingList1     1        10         100
ComparingList1     1        10         101
ComparingList1     1        11         100
ComparingList1     1        11         102
ComparingList1     1        11         103
ComparingList1     1        11         104

ComparingList2     2        10         100
ComparingList2     2        10         101
ComparingList2     2        11         100
ComparingList2     2        11         102
ComparingList2     2        11         103
ComparingList2     2        12         104
ComparingList2     2        12         105

查询

SELECT 
   ComparingList2.customerid as customerId,
   ComparingList1.storeid as expectedStoreId, 
   ComparingList2.storeid as actualStoreId
FROM Lists ComparingList2
LEFT JOIN Lists ComparingList1
   on ComparingList1.customerid = ComparingList2.customerid
WHERE 
   ComparingList1.listid = 1
   AND ComparingList2.listid = 2
   AND ComparingList2.storeid <> ComparingList1.storeid

这个查询给了我:

customerid   expectedStoreId   actualStoreId
   100             10                 11 
   100             11                 10 
   104             11                 12 

但我想要的结果是:

customerid         expectedStoreId      actualStoreId
   104                   11                   12

Fiddle

2 个答案:

答案 0 :(得分:4)

嗯,你很亲密。 我在你的where子句中添加了另一个条件,它给出了所需的结果,但是我不确定它将如何对实际数据执行。

以下是修改过的查询:

SELECT 
  ComparingList2.customerid as customerId,
  ComparingList1.storeid as expectedStoreId, 
  ComparingList2.storeid as actualStoreId
FROM Lists ComparingList2
LEFT JOIN Lists ComparingList1
  on ComparingList1.customerid = ComparingList2.customerid 
WHERE ComparingList1.listid = 1
AND ComparingList2.listid = 2
AND ComparingList2.storeid <> ComparingList1.storeid
AND NOT EXISTS -- Added this part
(
    SELECT 1 
    FROM Lists c
    WHERE ComparingList1.customerid = c.customerid
    AND ComparingList1.storeid = c.storeid
    AND c.listid = 2
)

答案 1 :(得分:3)

通过删除匹配项,您可以加入customerid上的其余值,如下所示:

;WITH list1 as
(
  SELECT storeid, customerid 
  FROM Lists
  WHERE listid = 1
  EXCEPT 
  SELECT storeid, customerid
  FROM Lists
  WHERE listid = 2
), list2 as
(
  SELECT storeid, customerid 
  FROM Lists
  WHERE listid = 2
  EXCEPT 
  SELECT storeid, customerid 
  FROM Lists
  WHERE listid = 1
)
SELECT 
  list1.customerid, 
  list1.storeid ExpectedStoreId,
  list2.storeid ActualStoreId
FROM list1 
JOIN list2 
ON list1.customerid= list2.customerid