gpt4 book ai didi

连接多个表时SQL Server SQL乘以Sum结果

转载 作者:行者123 更新时间:2023-12-02 01:14:34 25 4
gpt4 key购买 nike

如果有人能帮我解决这个问题,我将不胜感激。

我正在尝试从我使用 sum() 函数并连接另外两个表的一个表中获取结果。我的结果在 sum 列上成倍增加。这是我的表格的样子和我想要的结果

表一

[Id]   [Account_nbr]  [date]       [seq#]  
------------------------------------------
[1234] [$60] [4321] [10-15-2012] [1]
[1234] [$20] [4321] [10-15-2012] [2]
[1234] [$30] [4321] [10-15-2012] [3]
[2345] [$40] [9876] [10-15-2012] [1]
[3456] [$50] [6543] [10-15-2012] [1]

表2

[ID]      [cust_num]
---------------------
[1234] [8765]
[2345] [8766]
[3456] [8767]

表 3

[cust_num]     [account_nbr]
-------------------------------
[8765] [4321]
[8767] [9876]

我想要的结果是使用 ID 加入 Table 1Table 2 并使用 加入 Table 3 code>cust_num 并查看 table 1 中的 account_nbrTable 3 中的 account_number 匹配,如果然后找到匹配

sum(Table1.Amount),Table1.Id,Table1.Account_nbr,Table1.Date

我正在使用这样的 SQL 查询,但我的求和结果成倍增加

SELECT 
sum((Table1.Amount), Table1.Id, Table1.Account_nbr, Table1.Date
FROM
table1, table2, table3
WHERE
table1.id = table2.id
AND table2.cust_num = table3.cust_num
AND table1.account_nbr = table3.account_nbr
GROUP BY
table1.id,table1.account_nbr,table1.date
ORDER BY
table1.date DESC

但正如我之前所说,我的结果正在成倍增加。我想要的表格形式的结果如下所述

[Amount]     [Id]     [Account_nbr]    [Date]
---------------------------------------------------
[$110] [1234] [4321] [10-15-2012]
[$40] [2345] [9876] [10-15-2012]

id = 3456 不应该存在,因为 table1 中相应的 account_nbr 不存在于 table3 中。

最佳答案

如果 table1.id=table2.idtable2.cust_num=table3.cust_num 不是 1:1 关系,您将获得预期 SUM 的倍数。这称为笛卡尔积。 table1.account_nbr=table3.account_nbr 稍微减轻了它,但您仍然可以得到笛卡尔积。

  SELECT sum(Amount) Amount, Id, Account_nbr, Date
FROM table1
WHERE EXISTS (
SELECT 1
FROM table2
JOIN table3 on table2.cust_num = table3.cust_num
WHERE table1.id = table2.id
AND table1.account_nbr = table3.account_nbr)
GROUP BY id, account_nbr, date
ORDER BY date DESC

上面的查询仅从 table1 获得了相同的 SUM,同时测试了您是否可以在 t1-t2、t2-t3 和 t3-t1 之间获得匹配。

关于连接多个表时SQL Server SQL乘以Sum结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13096882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com