首页 > 解决方案 > 在非唯一条目上加入 SQL 查询

问题描述

我需要加入的两个表有问题。

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 不是唯一的。

请看我的例子:

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

标签: sqljoin

解决方案


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

从 table1, table2 where table1.orderid=table2.order_id group by order_id


推荐阅读