![](/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.