使用PostgreSQL with子句显示来自两个表的计数

时间:2014-10-30 11:56:18

标签: sql postgresql

我有四个表格广告,sales_enquiry,sales_estimate和sales_leadsource。使用的数据库是PostgreSQL。我想得到广告的sales_enquiry和sales_estimate的数量,广告和sales_enquiry的id为sales_leadsource为外键,sales_estimate表的id为sales_enquiry为外键。我尝试使用以下查询,但结果无法正确显示。

表架构

TABLE sales_leadsource
(
  leadsource_id serial NOT NULL,
  leadsource character varying(250),
  CONSTRAINT sales_leadsource_pkey PRIMARY KEY (leadsource_id)
)

TABLE advertisement
(
  id serial NOT NULL,
  ad_source_name character varying(200),
  amount numeric(18,2),
  duration character varying(50),
  leadsource_id integer,
  CONSTRAINT advertisement_pkey PRIMARY KEY (id),
  CONSTRAINT advertisement_leadsource_id_fkey FOREIGN KEY (leadsource_id)
      REFERENCES sales_leadsource (leadsource_id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE RESTRICT
)


TABLE sales_enquiry
(
  enquiry_id serial NOT NULL,
  leadsource_id integer,
  customer_name character varying(200),
  advertisement_id integer,
CONSTRAINT sales_enquiry_pkey PRIMARY KEY (enquiry_id),
  CONSTRAINT sales_enquiry_advertisement_id_fkey FOREIGN KEY (advertisement_id)
      REFERENCES advertisement (id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE RESTRICT
)


TABLE sales_estimate
(
  ref_no integer NOT NULL,
  enquiry_id integer,
  property_id integer,
  sqft_amount numeric,
CONSTRAINT sales_estimate_pkey PRIMARY KEY (ref_no),
  CONSTRAINT sales_estimate_enquiry_id_fkey FOREIGN KEY (enquiry_id)
      REFERENCES sales_enquiry (enquiry_id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE RESTRICT
)

查询如下

with campaign as(
select se.leadsource_id,se.advertisement_id,count(*) as leads_count from sales_enquiry se group by se.advertisement_id,se.leadsource_id
),
converted as(
select se.leadsource_id,se.advertisement_id,count(*) as converted_count from sales_enquiry se 
left join sales_estimate sm on se.enquiry_id=sm.enquiry_id
where sm.status_id=1 and sm.application_status=1 or sm.application_status=2
group by se.advertisement_id,se.leadsource_id
)
select a.id,
       coalesce(a.ad_source_name,'None'),
       a.amount,
       a.duration,
       c.leads_count,
       c.leadsource_id,
       sl.leadsource,
       cv.converted_count
       From advertisement a

       right join campaign c on a.id=c.advertisement_id
       left join converted cv on c.advertisement_id=cv.advertisement_id
       left join advertisement_status ads on a.status_id=ads.status_id
       left join sales_leadsource sl on c.leadsource_id=sl.leadsource_id;

请帮忙。提前谢谢。

0 个答案:

没有答案