gpt4 book ai didi

mysql - SQL 查询 - 贷方、借方、余额

转载 作者:行者123 更新时间:2023-11-29 06:31:17 27 4
gpt4 key购买 nike

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

表格如下:

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”语句(如子查询或自连接)?

最佳答案

当然。您可以使用带有 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

或者这样,使用带有内联 View 的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...

关于mysql - SQL 查询 - 贷方、借方、余额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27779114/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com