我确定这很简单,但我很挣扎!
我想要做的是从下表中返回ProductID,其中Mailed = True,但仅限于ProductID有一个供应商的地方。
在下面的示例中,我需要返回PRoductIDs 2和5而不是1
+-----------+----------+-------------+
| ProductID | Supplier | CanBeMailed |
+-----------+----------+-------------+
| 1 | A | False |
| 1 | B | True |
| 2 | C | True |
| 3 | C | False |
| 4 | D | False |
| 4 | E | False |
| 5 | E | True |
| 6 | F | False |
+-----------+----------+-------------+
有什么想法?
由于
答案 0 :(得分:4)
这适用于你之后的事情:
WITH VTE AS (
SELECT *
FROM (VALUES (1,'A',0),
(1,'B',1),
(2,'C',1),
(3,'C',0),
(4,'D',0),
(4,'E',0),
(5,'E',1),
(6,'F',0)) V(ProductID, Supplier, Mailed))
SELECT ProductID
FROM VTE
GROUP BY ProductID
HAVING SUM(CASE Mailed WHEN 'True' THEN 1 ELSE 0 END) > 0
AND COUNT(DISTINCT Supplier) = 1;