如何从表中找到唯一值

时间:2013-03-26 11:32:28

标签: sql sql-server

下面是我的名为companies

的表格
company_id        Status
1001                OFF
1002                OFF
1003                OFF
1003                ON

我需要避免使用company_id

的任何status 'ON'

我需要像下面那样放

company_id        Status
1001                OFF
1002                OFF

我如何为此编写查询

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

SELECT Company_Id, Status FROM Companies C 
WHERE NOT EXISTS(SELECT * FROM Companies 
WHERE Company_Id = C.Company_id AND Status = 'ON')

答案 2 :(得分:-1)

SELECT company_ID, MAX(Status) AS Status FROM companies
GROUP BY company_ID
HAVING MAX(Status) = 'OFF'

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