0

For example, if the below is the table

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

I am looking to fetch distinct suppliers whose all items are OOS or NULL.

One solution is to get all the suppliers who has atleast one active item (active suppliers) and then add a clause NOT IN active suppliers to pick non active supplier.

Is there any better way to achieve the same?

RaceBase
  • 18,428
  • 47
  • 141
  • 202

5 Answers5

2

One option, using aggregation:

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);

This assumes you want suppliers who have only all NULL or all OOS status. If you just want to limit to both these two status values, then use this:

SELECT SupId
FROM yourTable
GROUP BY SupId
HAVING SUM(CASE WHEN Status <> 'OOS' AND Status IS NOT NULL THEN 1 ELSE 0 END) = 0;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Try:

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')
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
0
SELECT DISTINCT SupId 
FROM Table 
WHERE SupId <> (
                 SELECT DISTINCT SupId 
                 FROM Table 
                 WHERE Status NOT IN ('OOS',NULL)
               )
akshay
  • 777
  • 4
  • 15
0

I would use NOT EXISTS :

SELECT t.*
FROM table t
WHERE NOT EXISTS (SELECT 1 FROM table t1 WHERE t1.supid = t.supid and t1.status <> 'OOS');
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
0

I would use group by and having:

select suppid
from t
group by suppid
having (min(Status) = 'OOS' and max(Status) = 'OOS') or
       min(Status) is null;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786