您能帮我this吗?
我想将金额列分为借方和贷方两列,并按帐户ID将借方和贷方总和分组
这是我的桌子:
ID | GeneralLedgerHeaderId | AccountId | DrCr | Ammount
1 | 1 | 2 | 1 | 200.000
2 | 1 | 4 | 1 | 200.000
3 | 1 | 5 | 2 | 428.000
4 | 1 | 8 | 1 | 28.000
5 | 2 | 5 | 1 | 428.000
答案 0 :(得分:4)
假设DrCr=1
表示借方,DrCr=2
表示贷方,则可以使用两个case
表达式:
SELECT AccountId,
SUM(CASE DrCr WHEN 1 THEN Amount END) AS sum_debit,
SUM(CASE DrCr WHEN 2 THEN Amount END) AS sum_credit
FROM mytable
GROUP BY AccountId
答案 1 :(得分:1)
您想要以下东西吗? 您可以将SUM()函数与Partition By子句一起使用,以便以Partition By子句中定义的自定义分类的方式获得Count()之类的聚合
select
Id,
GeneralLedgerHeaderId,
AccountId,
case when DrCr = 1 then Amount end as Debit,
case when DrCr = 2 then Amount end as Credit,
Summed = SUM(case when DrCr = 1 then (-1 * Amount) else Amount end) over (partition by AccountId)
from Transactions
将评论编辑到此帖子后的第二次查询
SELECT
GL.AccountId,
CA.Code,
CA.AccountName,
SUM(CASE GL.DrCr WHEN 1 THEN Amount END) AS sum_debit,
SUM(CASE GL.DrCr WHEN 2 THEN Amount END) AS sum_credit,
SUM(CASE GL.DrCr WHEN 1 THEN Amount ELSE (-1 * Amount) END) AS sum_total
FROM GeneralLedgerLine GL
Join COA_Client CC
on GL.AccountId = CC.AccountId
join ChartOfAccount CA
on CC.COA_Id = CA.COA_Id
GROUP BY
GL.AccountId, CA.Code, CA.AccountName
答案 2 :(得分:-1)
使用汇总时的用例,这里我假设DrCr = 1借项而2表示贷项
select accountid, sum(case when DrCr=1 then Amount end) as dr,
sum( case when DrCr=2 then Amount end) as cr from your_table
group by accountid