联合一个领域,但从其他表中加总其他领域

时间:2016-11-29 06:14:06

标签: sql postgresql

我有两个包含以下列的表:

SalesTable - invnum, brand, turnover, gp with values:

 1. Pepsi, 30000, 15000
 2. Coke, 40000, 20000
 3. Mountain Dew, 10000, 3000
 4. Dr Pepper, 5000, 2300
 5. Pepsi, 10000, 5000


SalesOrderTable - ordernum, brand, ordervalue, ordergp
with values:

 1. Pepsi, 50000, 25000
 2. Coke, 20000, 15000
 3. Vitamin Water, 30000, 12000
 4. Coke, 10000, 5000

我需要将两个表中的品牌列合并,以便显示两个表中的唯一值以及所有其他列的总和。结果应如下所示:

brand, inv_value, inv_gp, order_value, order_gp

Pepsi         40000 20000 50000 25000

Coke          40000 20000 30000 20000

Mountain Dew  10000  3000     0     0

Dr Pepper      5000  2300     0     0

Vitamin Water     0     0 30000 12000

谢谢!

3 个答案:

答案 0 :(得分:0)

试试这个 SELECT * FROM SalesTable NATURAL JOIN SalesOrderTable

答案 1 :(得分:0)

我认为这个要求也很好:通过union all和聚合函数简单易行:

select brand, 
    sum(t.turnover) turnover, 
    sum(t.gp) gp, 
    sum(t.ordervalue) ordervalue, 
    sum(t.ordergp) ordergp from 
    (
    select brand, turnover, gp, 0 ordervalue, 0 ordergp 
    from #SalesTable 
    union all
    select brand, 0, 0, ordervalue,ordergp 
    from #SalesOrderTable ) t group by t.brand

答案 2 :(得分:-1)

检查一下。

            create table #SalesTable
            (
            invnum int,
            brand varchar(20),
            turnover int,
            gp int
            )


            insert into #SalesTable values
            (1, 'Pepsi', 30000, 15000),
            (2,'Coke', 40000, 20000),
            (3,'Mountain Dew',10000,3000),
            (4,'Dr Pepper', 5000, 2300),
            (5,'Pepsi', 10000, 5000)


            create table #SalesOrderTable
            (
            ordernum int,
            brand varchar(20),
            ordervalue int,
            ordergp int
            )


            insert into #SalesOrderTable values
            (1,'Pepsi', 50000, 25000),
            (2,'Coke', 20000, 15000),
            (3,'Vitamin Water', 30000, 12000),
            (4,'Coke', 10000, 5000)


            select distinct 
            coalesce( st.brand,so.brand) as Brand,
            coalesce( st.turnover,'0') as inv_value,
            coalesce( st.gp,'0') as inv_gp,
            coalesce( so.ordervalue,'0') as order_value,
            coalesce( SO.ordergp,'0') as order_gp
            from
            (
            select brand,sum(ordervalue) as ordervalue ,sum(ordergp) as ordergp from  #SalesOrderTable
            group by brand
            )so 
             full outer join  
            (
            select brand,SUM(turnover) as turnover,SUM(gp) as gp from  #SalesTable
            group by brand
            )ST
            on SO.brand=ST.brandon SO.brand=ST.brand