我必须使用两个表来创建第三个表。 TableA不包含所需的所有信息,因为它仅列出了人们用来了解我们公司的来源,而TableB列出了人们可以使用的所有可能的来源。我希望TableC对未使用的源显示0%。在postgreSQL中这怎么可能?
select "Source", to_char(100 * count(*) / sum(count(*)) over (), '990%') as "The Ratio"
from TableA
group by "Source";
Source: The Ratio:
Website 55%
TV 25%
Radio 20%
Select * from Table2:
Source:
Website
TV
Radio
BillBoard
Referral
结果我谦卑地请求帮助:
Source: The Ratio:
Website 55%
TV 25%
Radio 20%
BillBoard 0%
Referral 0%
答案 0 :(得分:0)
您只想要一个left join
:
select a."Source",
to_char(100 * count(b.source) / sum(count(*)) over (), '990%') as "The Ratio"
from TableB b left join
TableA a
on a.source = b.source
group by a."Source";
答案 1 :(得分:0)
左边用table2连接结果:
select t2."Source", to_char(coalesce(t1."The Ratio",0),'990%') "The Ratio"
from table2 t2 left outer join
(select "Source", 100 * count(*) / sum(count(*)) over () "The Ratio"
from TableA
group by "Source") t1
on t1."Source" = t2."Source";