1

下面是我的表叫companies

company_id        Status
1001                OFF
1002                OFF
1003                OFF
1003                ON

company_id如果有的话,我需要避免status 'ON'

我需要像下面这样

company_id        Status
1001                OFF
1002                OFF

我如何为此编写查询

4

3 回答 3

3
SELECT  *
FROM    tableName
WHERE   company_ID NOT IN
        (
            SELECT company_ID 
            FROM    tableName
            WHERE   Status = 'ON'
        )

或通过使用LEFT JOIN

SELECT  a.*
FROM    tableName a
        LEFT JOIN
        (
            SELECT company_ID 
            FROM    tableName
            WHERE   Status = 'ON'
        ) b ON a.company_ID = b.company_ID
WHERE   b.company_ID IS NULL
于 2013-03-26T11:34:20.020 回答
3
SELECT Company_Id, Status FROM Companies C 
WHERE NOT EXISTS(SELECT * FROM Companies 
WHERE Company_Id = C.Company_id AND Status = 'ON')
于 2013-03-26T11:34:48.320 回答
-1
SELECT company_ID, MAX(Status) AS Status FROM companies
GROUP BY company_ID
HAVING MAX(Status) = 'OFF'

您可以使用 MIN 和 MAX 函数对字符串值进行排序。在这种情况下,MAX 将在 OFF 之前返回 ON。

于 2013-03-26T11:38:21.577 回答