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

时间:2012-10-27 03:07:14

标签: sql sql-server-2005

非常感谢任何人可以帮助我解决这个问题。

我试图从一个表中获取结果,其中我使用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]

我希望的结果将是使用Table 1加入Table 2ID并使用Table 3加入cust_num并查看来自{{1}的account_nbr }}与table 1中的account_number匹配,如果找到匹配则

Table 3

我正在使用这样的SQL查询,但我的总和结果是乘以

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

但就像我之前所说,我的结果正在成倍增加。我希望的结果以表格形式提供,如下所述

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_nbr的相应table1

3 个答案:

答案 0 :(得分:3)

嗯,这就是你需要的。我只是不明白你是如何在最终结果中获得2345的,可能是一个错字?

SQL FIDDLE Example

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

答案 1 :(得分:2)

如果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之间获得匹配。

答案 2 :(得分: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'