首页 > 解决方案 > 如果属性存在则为 1,否则为 0

问题描述

在以下查询中,为 1 小时时间间隔内出现的每个属性输出 1:

select t1.attribute, count(*)
from table1 t1
where timestamp >= trunc(sysdate-1/24, 'HH') and
      timestamp < trunc(sysdate, 'HH') and
      exists (select 1 from table2 t2 where t2.attribute = t1.attribute)
group by t1.attribute;

如何修改它以便为不在时间间隔内的每个属性也输出 0?

标签: sqloracle

解决方案


在您声明的table2具有完整属性列表的评论中。如果是这种情况,那么离开table1加入table2

select t2.attribute, count(t1.attribute)
from table2 t2
    LEFT OUTER JOIN table1 t1
        ON t2.attribute = t1.attribute 
        AND t1.timestamp >= trunc(sysdate-1/24, 'HH') 
        AND t1.timestamp < trunc(sysdate, 'HH')
group by t2.attribute;

将时间戳过滤器从WHERE子句转移到ON子句中,以LEFT OUTER JOIN确保table1在执行LEFT OUTER JOIN. 将在应用过滤器后LEFT OUTER JOIN从中选择所有记录,table2并且仅选择那些匹配的记录。table1

然后计算t1.attribute应该给你一个你想要的计数或0。最后对t2.attributefrom yourSELECT子句执行 GROUP BY。


推荐阅读