Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用另一个表中的相同ID对列中的值求和的SQL查询_Sql_Ms Access_Sum_Inner Join_Aggregate Functions - Fatal编程技术网

使用另一个表中的相同ID对列中的值求和的SQL查询

使用另一个表中的相同ID对列中的值求和的SQL查询,sql,ms-access,sum,inner-join,aggregate-functions,Sql,Ms Access,Sum,Inner Join,Aggregate Functions,我有两张像下面这样的桌子 table1 =========================== | table1_ID | table1_name | =========================== | 1 | A | | 2 | B | =========================== table2 ====================================== | table2_ID | t

我有两张像下面这样的桌子

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\u ID”具有相同ID的“table2\u数量”的总值”

我试过了,但结果不是我想要的

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
您还可以
加入
并聚合:

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
子句中使用逗号分隔的表

来自表1、表2
MS Access使用这种较旧的SQL语法,因为它的方言还不支持显式的
交叉连接
,无法清楚地显示您正在尝试的内容。在其他功能中,我有这样的支持

因此,聚合在两个表的上运行,这两个表成对匹配两个表中的每一行组合。所以你的分组和总数可能比预期的要大得多

要修复,只需将
交叉连接
转到
内部连接

选择t1.table1\u ID
,t1.table1\u名称
,总和(t2.表2数量)为总数量
来自表1 t1
内连接表2 t2
在t1.table1\u ID=t2.table1\u ID上
按t1.1\U ID分组
,t1.表1\u名称;

提示:
加入
<代码>分组依据
。你试过什么?