![](/img/trans.png)
[英]SQL Query to SUM values from column using the same ID from another table
[英]How to select sum of the values with same id from another table in SQL
我有两张桌子:
桌子套件
id_kit | id_product | quantity
1 | 5 | 5
1 | 4 | 2
1 | 10 | 10
2 | 12 | 1
2 | 20 | 2
表产品
id_product | pco_cost
5 | 100
4 | 50
10 | 20
12 | 10
20 | 5
我想要的结果
id_kit | cost_kit
1 | 800
每个产品的成本总和乘以数量 其中 id_kit = "x"
编辑:(从评论中复制):我试试这个:
SELECT
pco_cost * (SELECT pkt_quantity FROM cm_product_kit where kt_id_product_catalog = 20928) as pkt_cost
FROM cm_product_cost
where pco_prd_id_product = 20928
但只得到 1 个字段的结果,我希望所有具有相同 id 的项目返回每个产品的总和。
谢谢!
看起来像一个简单的聚合连接(过度乘法)。 第 1 - 15 行代表样本数据; 您需要的查询从第 16 行开始。
SQL> with
2 kit (id_kit, id_product, quantity) as
3 (select 1, 5, 5 from dual union all
4 select 1, 4, 2 from dual union all
5 select 1, 10, 10 from dual union all
6 select 2, 12, 1 from dual union all
7 select 2, 20, 2 from dual
8 ),
9 product (id_product, pco_cost) as
10 (select 5, 100 from dual union all
11 select 4, 50 from dual union all
12 select 10, 20 from dual union all
13 select 12, 10 from dual union all
14 select 20, 5 from dual
15 )
16 select k.id_kit, sum(k.quantity * p.pco_cost) cost_kit
17 from kit k join product p on k.id_product = p.id_product
18 group by k.id_kit
19 order by k.id_kit;
ID_KIT COST_KIT
---------- ----------
1 800
2 20
SQL>
DECLARE @tableKit TABLE (id_kit int, id_product int, quantity int)
INSERT INTO @tableKit VALUES
(1, 5 , 5)
, (1, 4 , 2)
, (1, 10 , 10)
, (2, 12 , 1)
, (2, 20 , 2)
DECLARE @tableProduct TABLE (id_product int, pco_cost int)
INSERT INTO @tableProduct VALUES
( 5 , 100)
, ( 4 , 50)
, (10 , 20)
, (12 , 10)
, (20 , 5)
SELECT
id_kit
, cost_kit = SUM(cost_kit)
FROM (
SELECT
id_kit = TK.id_kit
, cost_kit = TP.pco_cost * TK.quantity
FROM @tableKit TK
JOIN @tableProduct TP ON TP.id_product = TK.id_product
) R
GROUP BY id_kit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.