SUM WITH Left Join group by子句

时间:2018-01-08 16:28:56

标签: sql sql-server left-join inner-join

我有三个表有一个共同的列Ch_id。 我想在所有三个表中使用别名(Allocation,Received,Withdrawl,Balance)对列(总计)求和。

如何加入所有三个表并获得如下结果。

CH_id      Allocation   Received   Withdrawl   Balance(Received-Withdrawl)
--------------------------------------------------------------------------
1          100000       50000       25000       25000
2          300000       20000       200000      0
3          200000       100000      0           100000

...... and so on

我想要CH_Allocation表中的所有行

我尝试了以下但是没有给出预期的结果。

SELECT
    CH_Allocation.CH_id,
    SUM(CH_Allocation.Total) AS Allocated,
    SUM(ch_funds.Total) AS received,
    (req_ch.total) AS Withdrawl
FROM CH_Allocation 
LEFT JOIN Req_CH
    ON Req_CH.CH_id = CH_Allocation.CH_id
LEFT JOIN CH_Funds
    ON CH_Funds.CH_id = CH_Allocation.CH_id
WHERE
    CH_Allocation.Project_Id = 2 AND
    Req_CH.Project_id = 2
GROUP BY
    CH_Allocation.CH_id,
    Req_CH.ch_id,
    CH_Funds.CH_id

还有这个

select a.ch_id,SUM(a.total) as alloted,SUM(b.total) as received,SUM(c.total) as withdrawl,SUM(b.Total)-sum(c.Total) as balance from 
CH_Allocation a,CH_Funds b,Req_CH c
where a.CH_id=b.CH_id
and c.CH_id=b.CH_id
and b.CH_id=a.CH_id
and c.Project_id=2
and a.Project_Id=2
and b.Project_Id=2
group by a.CH_id

请帮助专家。

2 个答案:

答案 0 :(得分:0)

这有两种方法。一种是使用full join,但这很麻烦,因为会创建大量NULL值。第二种是将表合并在一起然后聚合:

SELECT CH_id,
       SUM(Allocated) AS Allocated,
       SUM(received) AS received,
       SUM(Withdrawal) AS Withdrawal
FROM ((SELECT Project_Id, ch_id, Total as allocated, 0 as received, 0 as Withdrawal
       FROM CH_Allocation 
      ) UNION ALL
      (SELECT Project_Id, ch_id, 0 as allocated, Total as received, 0 as Withdrawal
       FROM Req_CH 
      ) UNION ALL
      (SELECT Project_Id, ch_id, 0 as allocated, 0 as received, Total as Withdrawal
       FROM CH_Funds 
      ) 
     ) t
WHERE Project_Id = 2 
GROUP BY ch_id;

答案 1 :(得分:0)

最后,我设法通过以下查询来完成此操作。

    SELECT  a.CH_id AS CH_ID,isnull(t.allocated,0) AS allocated,
isnull(s.received,0) AS received,isnull(p.withdrawl,0) AS withdrawl,
isnull(received,0)-isnull(withdrawl,0) AS Balance 
FROM CH_Allocation a 
LEFT JOIN (SELECT  ch_id, sum(total) AS allocated FROM CH_Allocation
 where Project_Id=1 GROUP BY ch_id ) t 
 ON (a.id = t.ch_id) 
LEFT JOIN (  SELECT  ch_id, sum(total) AS received
FROM CH_Funds where Project_Id=1  GROUP BY ch_id) s ON (a.id = s.ch_id) 
LEFT JOIN (  SELECT ch_id, sum(Total) AS withdrawl  
FROM Req_CH where Project_Id=1 GROUP BY ch_id) p ON (a.id = p.ch_id)