如何通过ID列检索所有在状态列中具有值的行(而不是null)组。
Id Name Status
1394 Test 1 Y
1394 Test 2 null
1394 Test 3 null
1395 Test 4 Y
1395 Test 5 Y
我写了像 select * from table where status = 'Y'
一样。它带给我3个记录,如何增加条件以仅带来最后2个?1394 ID具有其他2个记录,哪个状态为null。
如果要选择状态为仅 y的组,则可以做:
select t.*
from t
where not exists (select 1
from t t2
where t2.id = t.id and
(t2.Status <> 'Y' or t2.status is null)
);
如果您只需要ID,我将使用group by
和having
:
select id
from t
group by id
having min(status) = 'Y' and max(status) = 'Y' and count(*) = count(status);
最后一个条件检查没有NULL
值。
您也可以写:
having min(status = 'Y' then 1 else 0 end) = 1
一种简单的方法是:
select * from mytable
where status = 'Y'
and id not in (select id from mytable where status is null)
现有查询" status ='y'"的现有查询将不会使您从定义上带来无效。
如果您试图获得分组结果,则" ID组"子句将实现这一目标,这也需要将ID放入Select中,而不是"*"。
示例: SELECT id, COUNT(id) from table where status = 'Y'
如果我正确阅读了此书,您想为从不具有零状态值的分组带来ID:
我将使用一个不存在的子查询:
SELECT DISTINCT ID FROM mytable WHERE status IS NULL;
然后,该列表中不存在的过滤ID:
SELECT * FROM mytable WHERE id NOT IN (SELECT DISTINCT ID FROM mytable WHERE status IS NULL);
这是一些可能的解决方案,因为我不清楚您想要什么作为输出:
Select Id, Name, Status from table where status is not null;
导致3行:
Id Name Status
1394 Test 1 Y
1395 Test 4 Y
1395 Test 5 Y
Select Id, count(*) as anAmt from table where status is not null group by Id;
/* only retrieves counts per Id */
每个ID的1行:
Id anAmt
1394 1
1395 2