sql - 如果属性存在则为 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?
解决方案
在您声明的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.attribute
from yourSELECT
子句执行 GROUP BY。
推荐阅读
- vb.net - 在 vb.net 中将图像存储到位图中
- c++ - 通过单击按钮显示和隐藏堆栈面板 [Visual Studios 2019 for C++]
- javascript - 如何防止美化扩展格式化内联 Javascript?
- amazon-web-services - AWS iot boto3 - 如何获得附加到事物的证书?
- java - 如何将 ConcurrentHashMap.merge() 与共享的 AtomicInteger 一起使用
- c# - 生成了新的迁移,但未应用于 Db
- android - 如何增加android volley请求超时
- node.js - 如何插入循环以检查数组中的每个值[mongoDB,Node.js]
- azure-devops - Azure DevOps - 更改原因
- python - 如何在 Reportlab 中引用模型