合并来自2个不同表的列以应用聚合函数

时间:2015-11-05 06:17:37

标签: postgresql merge

我有3张桌子

Create table products(
  prod_id character(20) NOT NULL,
  name character varying(100) NOT NULL,
  CONSTRAINT prod_pkey PRIMARY KEY (prod_id)
)
Create table dress_Sales(
  prod_id character(20) NOT NULL,
  dress_amount numeric(7,2) NOT NULL,
  CONSTRAINT prod_pkey PRIMARY KEY (prod_id),
  CONSTRAINT prod_id_fkey FOREIGN KEY (prod_id)
  REFERENCES products (prod_id) MATCH SIMPLE
  ON UPDATE NO ACTION ON DELETE NO ACTION
)
Create table sports_Sales(
  prod_id character(20) NOT NULL,
  sports_amount numeric(7,2) NOT NULL,
  CONSTRAINT prod_pkey PRIMARY KEY (prod_id),
  CONSTRAINT prod_id_fkey FOREIGN KEY (prod_id)
  REFERENCES products (prod_id) MATCH SIMPLE
  ON UPDATE NO ACTION ON DELETE NO ACTION
)

我希望从表中获得SumAverage销售额(仅适用于选定的Prod_id)。我尝试过以下代码,但它没有产生任何价值。

select sum(coalesce(b.dress_amount, c.sports_amount)) as total_Amount
from products a JOIN dress_sales b on a.prod_id = b.prod_id 
JOIN sports_sales c on a.prod_id = c.prod_id and a.prod_id = ANY( {"123456","456789"}')`

此处1000038923位于dress_sales表格中,8002265822位于sports_sales中。

2 个答案:

答案 0 :(得分:1)

您的产品看起来只能存在于一个表格中(dress_salessports_sales)。

在这种情况下,您应该使用left join

select
        sum(coalesce(b.dress_amount, c.sports_amount)) as total_amount,
        avg(coalesce(b.dress_amount, c.sports_amount)) as avg_amount
    from products a
    left join dress_sales b using(prod_id)
    left join sports_sales c using(prod_id)
        where
            a.prod_id in ('1', '2');

如果您使用inner join(默认设置),则产品行不会显示在结果集中,因为它不会与dress_salessports_sales结合使用。

答案 1 :(得分:1)

如果您的产品出现在两个表中,则可以使用可以处理dress_amountsports_amount值的子查询。

select sum(combined.amount), avg(combined.amount)
from
  (select prod_id, dress_amount as amount from dress_sales
   union all
   select prod_id, sports_amount as amount from sports_sales) combined
where
   combined.prod_id in ('1','2');