sql - How to count entities, factored in cases, when there's no objects satisfying the condition from join clause in SQL?
问题描述
I have a simple table with some data. I would like to write query, which returns "cas number" of objects, which have more "sent" rows, than "rent" rows. My query is attached below:
select
c1.cas
from
casdat c1
join
casdat c2
on
c1.cas=c2.cas
and c1.type='sent'
and c2.type='rent'
group by
c1.cas
having
count(distinct c1.data) > count(distinct c2.data);
The problem is, my query does not process a case, when some specific "cas" has few "sent" rows and 0 "rent" ones. How to include such a case for my query? I would like to keep the JOIN clause. I know i could write a subquery and count it like that:
select c1.cas,count(distinct c1.data) from casdat c1
where c1.type='sent'
group by c1.cas
having count(distinct c1.data)>
(select count(distinct c2.data) from casdat c2 where c2.type='rent' and
c2.cas=c1.cas);
I would like that my query works like the second one attached here, but i need to use join clause. How to write such a query?
解决方案
使用带有having
子句的聚合:
select c.cas
from casdat c
group by c.ca
having sum(case when c.type = 'sent' then 1 else 0 end) > sum(case when c.type = 'rent' then 1 else 0 end);
推荐阅读
- ios - 如何显示我的 TableView 控制器的 UILabel 文本?
- javascript - 如何使用主键和辅助键对数据进行非规范化
- hibernate - 当我使用 2 ManyToMany 关系时,HibernateJpaConfiguration java.lang.NullPointerException
- amazon-web-services - 在 AWS 上部署时未找到 hugo 命令
- google-chrome - 如何撤消在浏览器地址栏中输入的内容
- sql - 获得第二高的薪水,如果没有第二高则返回 null
- python-3.x - 滚动条不起作用,是否正确设置了滚动区域?
- video - 是否可以从网站重定向或获取实时视频数据?
- scala - 文档中的 Akka HTTP 路由 DSL 示例不起作用
- vba - VBA有没有办法在目录中找到一个字符串然后循环?