Sql 多联接查找计数子查询
我有下面的表,必须编写一个查询以获得下面的输出。我能够获得除opportunity\u published\u count之外的所有输出列。这基本上是一个有价值的机会计数。 当前查询:Sql 多联接查找计数子查询,sql,postgresql,Sql,Postgresql,我有下面的表,必须编写一个查询以获得下面的输出。我能够获得除opportunity\u published\u count之外的所有输出列。这基本上是一个有价值的机会计数。 当前查询: SELECT count(distinct opportunity_vendors.opportunity_id) as opportunity_count , vendors.name as vendor_name , count(applications.id) as appl
SELECT count(distinct opportunity_vendors.opportunity_id) as opportunity_count ,
vendors.name as vendor_name ,
count(applications.id) as applications_count
FROM public.vendors
inner join public.opportunity_vendors on vendors.id = opportunity_vendors.vendor_id
inner join public.opportunities on opportunity_vendors.opportunity_id = opportunities.id
inner join public.applications on opportunity_vendors.opportunity_id = applications.opportunity_id
group by vendors.name;
表结构
vendors
[id (PK) , vendor_name]
opportunity_vendors
[id (PK), opportunity_id,vendor_id] opp_id FK to opportunity , vendor_id FK to vendors
opportunities
[id (PK),opp_name,published] published is either true or false
applications
[id (PK),opportunity_id] opp_id FK to opportunity
输出
vendor_name | opportunity_count | opportunity_published_count | applications_count
Length
不是聚合函数,所以可以在WHERE
子句中使用它
试试这个
SELECT count(DISTINCT opportunity_vendors.opportunity_id) as opportunity_count ,
vendors.name as vendor_name ,
count(applications.id) as applications_count,
count(case when published = true then opportunities.id end) as opportunity_published_count ,
FROM public.vendors
inner join public.opportunity_vendors on vendors.id = opportunity_vendors.vendor_id
inner join public.opportunities on opportunity_vendors.opportunity_id = opportunities.id
inner join public.applications on opportunity_vendors.opportunity_id = applications.opportunity_id
WHERE length(vendors.name) > 0
group by vendors.name
我想您只需要
过滤器:
COUNT(DISTINCT opportunity_vendors.opportunity_id) FILTER (WHERE published) as opportunity_published_count ,
将WHERE子句改为长度(vendors.name)>0
条件。但是,您甚至不应该允许零长度的名称。你害怕空值吗?过滤器是如何工作的。我的opportunity\u供应商表不包含已发布列。已发布列位于opportunities表中。@AbhishekAnand。他们不必来自同一张桌子。这两列在联接后可用。您可以查看文档以了解过滤器:。