[英]How to select sum of the values with same id from another table in SQL
[英]SQL Query to SUM values from column using the same ID from another table
我有如下兩張表;
table1
===========================
| table1_ID | table1_name |
===========================
| 1 | A |
| 2 | B |
===========================
table2
======================================
| table2_ID | table2_qty | table2_ID |
======================================
| 22 | 4 | A |
| 23 | 9 | A |
| 24 | 12 | B |
| 25 | 23 | B |
======================================
輸出應該是這樣的:
================================
| table1_ID | name | total_qty |
================================
| 1 | A | 13 |
| 2 | B | 35 |
================================
“table2 ID,名稱和與'table1_ID'相同ID的'table2_qty'的總和值”
我試過了,但結果不是我想要的。
SELECT table1.table1_ID, table1.table1_name,
SUM(table2.table2_qty) As total_qty
FROM table1, table2
GROUP BY table1.table1_ID, table1.table1_name;
如何在 SQL 中得到結果?
謝謝!
這是一個使用相關子查詢的選項:
select t1.*,
(
select sum(t2.table2_qty)
from table2 as t2
where t2.table2_id = t1.table1_name
) as total_qty
from table1 as t1
您還可以join
和聚合:
select t1.table1_id, t1.table1_name, sum(t2.table2_qty) as total_qty
from table1 t1
left join table2 t2 on t2.table2_id = t1.table1_name
group by t1.table1_id, t1.table1_name
您可以使用嵌套查詢:
select t1.table1_id, t2.name, t2.total_qty
from table1 t1
join (
select table2_id name, sum(table2_qty) total_qty
from table2
group by table2_id
) t2 on t2.name = t1.table1_name;
本質上,您的嘗試是在交叉連接查詢上聚合,因為您在FROM
子句中使用逗號分隔的表。
FROM table1, table2
MS Access 使用這種較舊的 SQL 語法,因為它的方言尚不支持明確的CROSS JOIN
以清楚地顯示您正在嘗試的內容。 我在其他功能中建議了這種支持。
因此,您的聚合在兩個表的笛卡爾積上運行,它們成對匹配兩個表中行的每個組合。 因此,您的分組和總數可能比預期的要大得多。
要修復,只需將CROSS JOIN
轉換為INNER JOIN
:
SELECT t1.table1_ID
, t1.table1_name
, SUM(t2.table2_qty) AS total_qty
FROM table1 t1
INNER JOIN table2 t2
ON t1.table1_ID = t2.table1_ID
GROUP BY t1.table1_ID
, t1.table1_name;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.