根据列中的值对行组进行求和

时间:2018-06-04 08:50:43

标签: sql-server tsql

我是SQL新手,我有下表

Table Data

我需要在下面选择并获得所需的结果。 Desired Result

1 个答案:

答案 0 :(得分:0)

尝试如下查询。

select  
    [Account Group] =AG.Name,
    [Ledger Name]   =AL.Name,
    DR  =SUM(CASE WHEN TT.Name='DR' THEN Amount ELSE NULL END),-- case based SUM expression
    CR  =SUM(CASE WHEN TT.Name='CR' THEN Amount ELSE NULL END)
from Account_Group AG
join Account_ledgers AL -- NOTE  we have used INNER JOIN throughout
    on AG.Id=AL.AccountGroupId
join Transactions  T
    on T.AccountLedgerId=AL.Id
join Transaction_Type TT
    on TT.Id= T.TransactionTypeId
group by AG.Name,AL.Name -- Group by contains all the things we need in SELECT list