繁体   English   中英

SQL查询-贷方,借方,余额

[英]SQL query - credit , debit , balance

免责声明: 我知道这个问题已经被问过很多遍了,但是我想要的只是一个替代方案。

下表如下:

create table 
Account
(Name varchar(20),
 TType varchar(5),
 Amount int);

insert into Account Values
('abc' ,'c', 500),
 ('abc', 'c', 700),
 ('abc', 'd', 100),
 ('abc', 'd', 200),

('ab' ,'c', 300),
 ('ab', 'c', 700),
 ('ab', 'd', 200),
 ('ab', 'd', 200);

预期结果很简单:

 Name     Balance
 ------  -----------
ab         600
abc        900

工作的查询是:

select Name, sum(case TType when 'c' then Amount
                    when 'd' then Amount * -1 end) as balance 
from Account a1 
group by Name.

我想要的是,对于相同的结果,是否有任何查询都没有'case'语句(例如subquery或self join)?

当然。 您可以使用带有where子句和并union all的第二个查询:

select name
,      sum(Amount) balance
from   Account a1
where  TType when 'c'
group
by     Name
union
all
select name
,      sum(Amount * -1) balance
from   Account a1
where  TType when 'd'
group
by     Name

还是这个,使用join与内嵌视图:

select name
,      sum(Amount * o.mult) balance
from   Account a1
join   ( select 'c' cd
         ,      1 mult
         from   dual
         union all
         select 'd'
         ,      -1
         from   dual
       ) o
on     o.cd = a1.TType
group
by     Name

老实说,我建议用case ...

使用char的ASCII码,然后尝试从那里开始。 “ d”为100,“ c”为99。 未经测试的示例:

select Name, sum((ASCII(TType) - 100) * Amount * (-1))  + sum((ASCII(TType) - 99) * Amount * (-1)))) as balance from Account a1 group by Name.

我不建议使用此方法,但这是一种实现您想要的方法。

select t.Name, sum(t.cr) - sum(t.dr) as balance from (select Name, case TType when 'c' then sum(Amount) else 0 end as cr, case TType when 'd' then sum(Amount) else 0 end as dr from Account group by Name, TType) t group by t.Name;

这一定会对您有帮助!!

以下在Microsoft SQL Server上为我工作。 它也具有结转余额

WITH tempDebitCredit AS (
Select 0 As Details_ID, null As Creation_Date, null As Reference_ID, 'Brought 
Forward' As Transaction_Kind, null As Amount_Debit, null As Amount_Credit, 
isNull(Sum(Amount_Debit - Amount_Credit), 0) 'diff'
From _YourTable_Name
where Account_ID = @Account_ID
And Creation_Date < @Query_Start_Date
Union All
SELECT a.Details_ID, a.Creation_Date, a.Reference_ID, a.Transaction_Kind, 
a.Amount_Debit, a.Amount_Credit, a.Amount_Debit - a.Amount_Credit 'diff'
FROM _YourTable_Name a
where Account_ID = @Account_ID
And Creation_Date >= @Query_Start_Date And Creation_Date <= @Query_End_Date
)

SELECT a.Details_ID, a.Creation_Date, a.Reference_ID, a.Transaction_Kind, 
a.Amount_Debit, a.Amount_Credit, SUM(b.diff) 'Balance'
FROM   tempDebitCredit a, tempDebitCredit b
WHERE b.Details_ID <= a.Details_ID
GROUP BY a.Details_ID, a.Creation_Date, a.Reference_ID, a.Transaction_Kind, 
a.Amount_Debit, a.Amount_Credit
Order By a.Details_ID Desc

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM