TSQL - 排除仅满足条件的用户

时间:2012-07-25 20:31:29

标签: sql sql-server tsql

我已经被困在这一天差不多整整一天了,我似乎无法让查询返回给我想要的结果集,我甚至不知道如何正确地说出这个问题我是面对。

目标是排除或以其他方式标记拥有ItemNumber记录的客户,例如“9%”。

    CustomerID  ItemNumber
    85610           99
    85611           11
    85611           99
    85612           13
    85612           11
    85612           98
    85613           98
    85613           99

在此示例中,应排除或标记CustomerIDs 86510和86513,因为与其记录关联的唯一ItemNumbers类似于'9%'。

我会坚持下去,但我感觉这是一件非常简单的事情,我忽视了,我很感激你的帮助。

麦克

5 个答案:

答案 0 :(得分:6)

SELECT CustomerID, ItemNumber
  FROM dbo.table AS t
  WHERE NOT EXISTS
  (
    SELECT 1 FROM dbo.table 
     WHERE CustomerID = t.CustomerID 
     AND ItemNumber NOT LIKE '9%'
  );

答案 1 :(得分:2)

SELECT 
    CustomerID
FROM Table T
WHERE NOT EXISTS (SELECT CustomerID FROM Table WHERE CustomerId = T.CustomerId AND ItemNumber NOT LIKE '9%')

答案 2 :(得分:2)

另一个选择

SELECT CustomerID
FROM YourTable
GROUP BY CustomerID
HAVING MAX(CASE WHEN ItemNumber LIKE '9%' THEN 1 END) = 1
    AND MAX(CASE WHEN ItemNumber NOT LIKE '9%' THEN 1 END) IS NULL

答案 3 :(得分:0)

create table tc(CustomerID int,ItemNumber varchar(10))

INSERT INTO tc
VALUES(85610,99),
    (85611,11),
    (85611,99),
    (85612,13),
    (85612,11),
    (85612,98),
    (85613,98),
    (85613,99)

select CustomerID from tc 
where ItemNumber like '9%'
group by CustomerID 

except

select CustomerID from tc 
where ItemNumber not like '9%'
group by CustomerID 

答案 4 :(得分:-1)

除非我遗漏了某些内容,为什么不包含WHERE <{1}}条款ItemNumber NOT LIKE '9%'