在非唯一条目上具有联接的SQL查询

时间:2018-12-05 11:02:28

标签: sql join

我需要连接两个表时遇到问题。

Table1

Order_id              Item_Revenue            Item_id
1                     30 €                    22222222
1                     20 €                    11111111
1                     10 €                    33333333
2                     5 €                     55555555

Table2

package_id           Order_id                 shipping_costs
456                  1                        1 €
567                  1                        2 €
789                  1                        3 €
999                  2                        2 €

我需要的输出:我想显示每个Order_Id的商品收入和运输费用

Order_ID          count(item_id)      sum(item_revenue)  sum(shipping_costs)
1                 3                   60 €                6 €
2                 1                   5 €                 2 €

我的第一次尝试是:

Select
sum(t1.item_revenue),
count(t1.item_id),
sum(t2.shipping_costs),
from table1 t1
left join table2 t2 on t1.order_id = t2.order_id
group by t1.order_id

但是它不起作用,因为order_id不是唯一的。

请看我的例子:

如果有人能帮助我,我会很幸运。

5 个答案:

答案 0 :(得分:0)

我认为您需要内部联接

    Select order_id,count( distinct item_id),
    sum(item_revenue),
    sum(shipping_costs)
    from table1
    join table2 on table1.order_id = table2.order_id
    group by order_id

答案 1 :(得分:0)

您的别名和逗号缺失问题。 在GROUP BY中使用了“ order_id”,但是您需要定义与Table1或Table2相关的字段。 另外,为别名。不要以1,2之类的数字开头。您会收到错误消息。

编辑(子查询中的表2):

Select
    T1.order_id
    ,count(1) ItemCount
    ,sum(item_revenue) ItemRevenue
    ,sum(shipping_costs) ShippingCost
from table1 T1
INNER join (SELECT Order_id
                  ,SUM(shipping_costs) shipping_costs  
            FROM Table2
            GROUP BY Order_id) T2 on T1.order_id = T2.order_id
group by T1.order_id

答案 2 :(得分:0)

希望对您有帮助,并假设您正在使用Oracle SQL

select table1.Order_id
sum(table1.item_revenue)
count(table1.item_id)
sum(table2.shipping_costs)
from
(
  select Order_id,Item_Revenue,Item_id, row_number() over (partition by Order_id order by Item_id) as man_id
  from table 1
)
table1
left join
(
  select package_id,Order_id,shipping_costs, row_number() over (partition by Order_id order by package_id) as man_id
  from table 2
)
table2
on table1.order_id = table2.order_id
and table1.man_id = table2.man_id
group by table1.order_id

答案 3 :(得分:0)

select order_id , count(item_id), sum(item_revenue) , sum(shipping_costs)

来自表1,表2 其中table1.orderid = table2.order_id 按order_id分组

答案 4 :(得分:0)

总结连接前的两个表。然后使用join full join来获得两个表中的所有订单:

select coalesce(t1.order_id, t2.order_id) as order_id,  -- include the order_id
       t1_revenue, t1_count,
       shipping_costs
from (select t1.order_id, sum(t1.item_revenue) as t1_revenue, count(*) as t1_count
      from table1 t1
      group by t1.order_id
     ) t1 full join
     (select t2.order_id, t2.shipping_costs as shipping_costs
      from table2 t2
      group by t2.order_id
     ) t2
     on t1.order_id = t2.order_id;

如果您的数据库不支持full join,请使用left join。大概table2中的订单也在table1中。