仅选择“客户”的所有行具有相同状态的位置?

时间:2013-05-02 09:32:16

标签: sql-server tsql select

我的状态表包含位字段closed

我想尝试选择所有CustomerNumber s,其中该客户的所有行均为closed

以下作品......但我确信有更明智的方法可以做到这一点!

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 两者的所有状态都为已关闭。

2 个答案:

答案 0 :(得分:3)

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

输出

╔════════════════╗
║ CUSTOMERNUMBER ║
╠════════════════╣
║            113 ║
║            114 ║
╚════════════════╝

答案 1 :(得分:3)

另一种解决方法是:

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

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