第一篇文章。
我有一个表格,我想计算出某个值出现的行。总的来说,我想要两个count()行,这些行依赖于另一列(Y和N)中的不同值。我认为最好在桌面上进行两次连接。但是,结果根本就没有行。 id是唯一的(主键)。
我缺少什么?它们相互取消,因为如果我只运行一个连接和相应的count()就可以了。或者,如果有更好的方法来解决这个问题。谢谢!
select
a.loans,
count(b.loans) as count_new_cust,
count(c.loans) as count_old_cust
FROM applications a
,(SELECT distinct id, loans FROM applications where new_cust='Y') b
,(SELECT distinct id, loans FROM applications where new_cust='N') c
where a.id=b.id and b.id=c.id
group by a.loans
order by a.loans DESC
答案 0 :(得分:4)
无需JOIN
。您可以改为使用条件聚合:
select a.loans,
count(case when new_cust='Y' then a.loans END) as count_new_cust,
count(case when new_cust='N' then a.loans END) as count_old_cust
FROM applications a
group by a.loans
order by a.loans DESC