列求和并连接两个表时返回double count

q9rjltbz  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(235)

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

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

谁能帮我弄到这个吗。

jaql4c8m

jaql4c8m1#

试试下面的方法-

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

相关问题