我有两张桌子,我需要对它们进行计数。
table1: id
table2: cid (table1.id = table2.cid) -- Join can be done by this.
我已经有两个正在使用的查询,想将它们放在一个查询中。
查询相关table1
:
WITH c_status AS (
select
CASE
WHEN regdate = 1 THEN 'yes'
WHEN regdate = 2 THEN 'no'
from table1
end as status_1
)
select status_1, count(*) AS c_status_count from c_status group by status_1
输出:
yes 548
no 2269
查询相关table2
:
WITH u_status AS (
select
CASE
WHEN regdate = 1 THEN 'yes'
WHEN regdate = 2 THEN 'no'
from table2
end as status_2
)
select status_2, count(*) AS u_status_count from u_status group by status_2
输出:
yes 564256
no 31452345234
问题:
如何将这两个查询放在一起?我想要一个单一的查询来报告这两个计数。
更新:所需的输出:
u_status yes 548
u_status no 2269
c_status yes 564256
c_status no 31452345234
您想要的可以通过以下方式实现:
注意:小技巧:
sum(case when regdate = 1 then 1 end)
实际上是计算regdate = 1
满足条件的次数;当语句返回 NULL 时regdate <> 1
,case
在这种情况下实际上不会对 1 求和。您也可以使用 a
count(*) filter
而不是 asum(case when ...)
,尽管我不确定这是否可以在 9.3 版中完成(我已经在 9.4 上测试过):dbfiddle在这里