【问题标题】:while summing of column and joining two tables returns double count而对列求和并连接两个表会返回双倍计数
【发布时间】:2020-11-12 18:41:30
【问题描述】:

我有两个表,我对它们执行了内部连接: 以下是我的查询

SELECT a.ship_id AS ship_id,
       sum(a.qty) as total_qty
from table_a as a
inner join table_b on a.shp_id = b.shpid
group by a.shp_id

Sample data:

table_a
-----------------------------
product_name | qty | ship_id
-----------------------------
item_1       | 10  | 1
item_2       | 20  | 1
item_3       | 10  | 2
item_4       | 10  | 2

table_b
-------------------
ship_id | desc
-------------------
1       | desc_1
2       | desc_2

我得到上述查询的输出如下:

--------------------
ship_id | total_qty
--------------------
1       | 60
2       | 40 

预期输出:

--------------------
ship_id | total_qty
--------------------
1       | 30 
2       | 20

谁能帮我弄到这个。

【问题讨论】:

  • 您的查询看起来不错,根据您提供的数据应该返回您想要的结果。

标签: sql sum inner-join


【解决方案1】:

试试下面的方法-

select a.ship_id,totalqty
from
(SELECT ship_id AS ship_id,
       sum(qty) as totalqty
from table_a group by ship_id) as a
inner join table_b on a.shp_id = b.shpid

【讨论】:

  • @MiteshBhanushali,没有聚合的加入会复制您的行,因为船舶表中没有项目引用。这就是为什么您需要在第一个表中进行聚合然后加入第二个表的原因。
猜你喜欢
  • 1970-01-01
  • 2021-10-09
  • 2017-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2021-12-09
  • 1970-01-01
相关资源
最近更新 更多