[英]Rails + Postgres query for all records that meet a criteria with a unique association ID
[英]Returning only id's of records that meet criteria
我需要返回满足以下条件的记录的不同ID:必须具有字段reason_of_creation = 1的记录,并且必须不具有字段reason_of_creation = 0或同时为null的记录。 虽然我能够做到这一点,但我一直在想是否有更优雅(甚至推荐)的方式。
这是我拥有的匿名版本:
select distinct st.some_id from (
select st.some_id, wanted.wanted_count as wanted, unwanted.unwanted_count as unwanted
from some_table st
left join (
select st.some_id, count(st.reason_of_creation) as wanted_count
from some_table st
where st.reason_of_creation=1
group by st.some_id
) wanted on wanted.some_id = st.some_id
left join (
select st.some_id, count(st.reason_of_creation) as unwanted_count
from some_table st
where st.reason_of_creation=0
group by st.some_id
) unwanted on unwanted.some_id = st.some_id
where wanted.wanted_count >0 and (unwanted.unwanted_count = 0 or unwanted.unwanted_count is null)
) st;
样本数据 :
some_id reason_of_creation
1 1
1 0
2 1
3 null
4 0
4 1
5 1
期望的结果将是some_id = 2, 5
的记录列表
在我看来你的查询是矫枉过正,你需要的只是一些后期聚合过滤
SELECT some_id FROM t
GROUP BY some_id
HAVING SUM(CASE WHEN reason_of_creation = 1 THEN 1 ELSE 0 END)>0
AND SUM(CASE WHEN reason_of_creation = 0 OR reason_of_creation IS NULL THEN 1 ELSE 0 END)=0
我认为存在更优雅的查询,它基于假设reasoson_of_crdeation字段是整数,所以最小可能它的值,大于0是1
这是针对reasoson_of_crdeation可能的负值:
select someid from st
where reasoson_of_crdeation != -1
group by someid
having(min(nvl(abs(reasoson_of_crdeation), 0)) = 1)
要么
select someid from st
group by someid
having(min(nvl(abs(case when reasoson_of_crdeation = -1 then -2 else reasoson_of_crdeation end), 0)) = 1)
如果reasoson_of_crdeation是非负整数,则在这种情况下:
select someid from st
group by someid
having(min(nvl(reasoson_of_crdeation, 0)) = 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.