SQL选择项在所有行中具有相同的值

时间:2018-08-01 06:35:57

标签: sql sql-server

例如,如果下面是表

SupId    ItemId          Status
1        1               Available
1        2               OOS
2        3               Available
3        4               OOS
3        5               OOS
4        6               OOS
5        7               NULL

我希望获取all items为OOS或NULL的其他供应商。

一种解决方案是让所有具有至少一个活跃项目的供应商(活跃供应商),然后添加条款NOT IN活跃供应商以选择非活跃供应商。

有没有更好的方法可以达到相同的目的?

5 个答案:

答案 0 :(得分:2)

使用聚合的一个选项:

SELECT SupId
FROM yourTable
GROUP BY SupId
HAVING
    SUM(CASE WHEN Status = 'OOS' OR Status IS NULL THEN 1 ELSE 0 END) = COUNT(*) AND
    (MAX(Status) = 'OOS' OR COUNT(Status) = 0);

这假设您希望所有供应商都具有所有NULL或所有OOS状态。如果您只想同时限制这两个状态值,请使用以下命令:

SELECT SupId
FROM yourTable
GROUP BY SupId
HAVING SUM(CASE WHEN Status <> 'OOS' AND Status IS NOT NULL THEN 1 ELSE 0 END) = 0;

答案 1 :(得分:0)

尝试:

SELECT DISTINCT SupId FROM my_table t
WHERE NOT EXISTS(SELECT 1 FROM my_table
                 WHERE SupId = t.SupId
                   AND [Status] IS  NOT NULL 
                   AND [Status] <> 'OOS')

答案 2 :(得分:0)

SELECT DISTINCT SupId 
FROM Table 
WHERE SupId <> (
                 SELECT DISTINCT SupId 
                 FROM Table 
                 WHERE Status NOT IN ('OOS',NULL)
               )

答案 3 :(得分:0)

我会使用NOT EXISTS

SELECT t.*
FROM table t
WHERE NOT EXISTS (SELECT 1 FROM table t1 WHERE t1.supid = t.supid and t1.status <> 'OOS');

答案 4 :(得分:0)

我将使用group byhaving

select suppid
from t
group by suppid
having (min(Status) = 'OOS' and max(Status) = 'OOS') or
       min(Status) is null;