gpt4 book ai didi

SQL 3 加入 group by 和 sum 函数

转载 作者:行者123 更新时间:2023-12-04 20:56:40 26 4
gpt4 key购买 nike

<分区>

我有3张 table
Tb代码表

    codevalue | codename | desc1 | desc2 
1 | SATO | NAG | Naga
2 | SATO | BAG | Baguio
3 | SATO | NCR | Head Office

Tb成员

employeeno | capcon_accountno | savings_accountno | sato
1 | 00101 | 00201 | NCR
2 | 00102 | 00202 | BAG

存款

employeeno | account_no | accountbalance
1 | 00101 | 1000
1 | 00201 | 5000
2 | 00102 | 1000
2 | 00202 | 5000

我要查询的是一次查询中每个sato的资本和储蓄之和

codename | codevalue | desc1      | desc2 | capcon | savings
SATO |3 |Head Office |NCR |1000 | 5000
SATO |2 |Baguio |BAG |1000 | 5000
SATO |1 |Naga |NAG |0 | 0

我能做的最好的查询是

SELECT codename,codevalue,desc1,desc2,sum(b.accountbalance) as capcon 
FROM TBCODETABLE c
left join TBMEMBER a on c.desc2 = a.SatoCode
join tbdeposit b on a.employeeno = b.employeeno
where a.SLAStatus = 'A' and c.codename ='sato'
group by codename, codevalue, desc1, desc2

这给了我这个结果

codename | codevalue | desc1      | desc2 | capcon
SATO |1 |Head Office |NCR |1000
SATO |2 |Baguio |BAG |1000

这只给出了资本总和(我不知道如何在结果中同时包括储蓄和资本。)它不包括纳迦地区

我可以通过 employeeno 加入 tbmember 和 tbdeposit 但我不知道如何在结果集中分离资本和储蓄的总和

编辑
我编辑了查询,现在由于 syed,我可以同时查询这两个查询,但我仍然无法获得 NAG sato 代码。查询:

SELECT codename,codevalue,desc1,desc2, coalesce(sum(b.accountbalance),0) as savings, coalesce(sum(bb.accountbalance),0) as capcon FROM TBCODETABLE c left join TBMEMBER a on c.desc2 = a.SatoCode join tbdeposit b on a.SAVINGS_AccountNo = b.AccountNo 
inner join tbdeposit bb on a.CAPCON_Accountno = bb.AccountNo where a.SLAStatus = 'A'
group by codename, codevalue, desc1, desc2

我能够得到预期的结果,谢谢你们 chris 的左连接建议解决了我的 NAG SATO 问题,尽管 Syed 的回复对我帮助很大。
我不知道怎么给回复投票,所以我只会给克里斯投票(第一次来这里。)

我的最终查询是:

SELECT codename,codevalue,desc1,desc2, coalesce(sum(b.accountbalance),0) as savings, coalesce(sum(bb.accountbalance),0) as capcon FROM TBCODETABLE c left join TBMEMBER a on c.desc2 = a.SatoCode left join tbdeposit b on a.SAVINGS_AccountNo = b.AccountNo 
left join tbdeposit bb on a.CAPCON_Accountno = bb.AccountNo where a.SLAStatus = 'A' or codename = 'sato'
group by codename, codevalue, desc1, desc2

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