2

我有一个带有位字段的状态表closed

我想尝试选择CustomerNumber该客户的所有行所在的所有 sclosed

以下工作......但我确信有一种更明智的方法!

SELECT * FROM
    (SELECT
          lcs.CustomerNumber AS CustomerNumber
        , COUNT(lcs.CustomerNumber) AS Total
    FROM Status lcs
    GROUP BY lcs.CustomerNumber) total
LEFT JOIN
    (SELECT
        lcs.CustomerNumber AS CustomerNumber
        , COUNT(lcs.CustomerNumber) AS Closed
    FROM Status lcs
    WHERE lcs.Closed = 1
    GROUP BY lcs.CustomerNumber) closed
ON closed.CustomerNumber = total.CustomerNumber
WHERE closed.Closed = total.Total

每个客户可以有一行或多行,每行已关闭=0 或已关闭=1

只有当客户的所有行都关闭时,我才需要选择。

样本:

CustomeNumber     Closed
111               0
111               0
112               1
112               0
113               1
113               1
114               1

这应该选择: 113 和 114 两者的所有状态都为已关闭。

4

2 回答 2

3
SELECT  customerNumber
FROM    TableName
GROUP   BY customerNumber
HAVING  COUNT(*) = SUM(CASE WHEN closed = 1 THEN 1 END)

输出

╔════════════════╗
║ CUSTOMERNUMBER ║
╠════════════════╣
║            113 ║
║            114 ║
╚════════════════╝
于 2013-05-02T09:36:45.913 回答
3

另一种解决方法是:

SELECT CustomerNumber FROM Status WHERE closed = 1
EXCEPT
SELECT CustomerNumber FROM Status WHERE closed = 0

EXCEPT返回的值将是不同的,因此无需添加。

于 2013-05-02T10:26:19.560 回答