2

如果有人可以帮助我解决这个问题,我们将不胜感激。

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

表格1

[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]

我想要的结果将是 join Table 1Table 2usingID和 join Table 3usingcust_num和 see account_nbrfromtable 1account_numberin匹配Table 3,如果找到匹配则

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不应该在那里,因为相应的account_nbrfrom 中table1不存在table3

4

3 回答 3

3

好吧,这就是你需要的。我只是不明白您的最终结果是如何得到 2345 的,可能是拼写错误?

SQL FIDDLE 示例

select
    sum(T1.Amount) as Amount,
    T1.Id,
    T1.account_nbr,
    T1.date
from table1 as T1
    inner join table2 as T2 on T2.Id = T1.Id
    inner join table3 as T3 on T3.cust_num = T2.cust_num and T3.account_nbr = T1.account_nbr
group by
    T1.Id,
    T1.account_nbr,
    T1.date
于 2012-10-27T05:32:32.683 回答
2

table1.id=table2.id如果table2.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 之间获得匹配。

于 2012-10-27T04:11:10.423 回答
0

我认为最好先计算总和,然后进行所有其他操作。

SELECT T1.amount AS Amount, 
       T1.id, 
       T1.account_nbr, 
       T1.DATE 
FROM   (SELECT SUM(t1.amount) AS Amount, 
               t1.id, 
               t1.account_nbr, 
               t1.DATE 
        FROM   table1 
        GROUP  BY t1.id, 
                  t1.account_nbr, 
                  t1.DATE)AS T1 
       inner join table2 AS T2 
               ON T2.id = T1.id 
       inner join table3 AS T3 
               ON T3.cust_num = T2.cust_num 
                  AND T3.account_nbr = T1.account_nbr'
于 2018-02-22T14:19:03.833 回答