当前位置:  开发笔记 > 编程语言 > 正文

使用多个聚合列和多个where子句编写查询的最佳方法是什么

如何解决《使用多个聚合列和多个where子句编写查询的最佳方法是什么》经验,为你挑选了1个好方法。

我有一张桌子tbl_LEDGER

+-----------+--------+-----+
| AccountId | GlCode | Amt |
+-----------+--------+-----+
| LAS00001  | INTRAC | 100 |
| LAS00002  | INTRAC | 150 |
| LAS00001  | INTLAS | 200 |
+-----------+--------+-----+

期望的结果:

+-----------+------------+-----------+
| AccountId | intractamt | intlasAmt |
+-----------+------------+-----------+
| LAS00001  |        100 |       200 |
| LAS00002  |        150 |         0 |
+-----------+------------+-----------+

这是我的工作查询:

select accountid,sum(amt) intracamt,  (select SUM(amt)  from tbl_LEDGER 
where   GLCode='intlas' and AccountID=intrac.AccountID ) intlasamt 
from tbl_LEDGER intrac 
where GLCode='intrac'    group by AccountID    order by AccountID

另一个工作查询:

select a.accountId,a.amt as 'RACAMT',b.amt as 'LACAMT' from 
(
select accountid ,glcode, SUM(amt) as amt from nbfcledger where GLCode='intrac' group by GLCode,AccountID 
) a
inner join 
(
select accountid ,glcode, SUM(amt) as amt from nbfcledger where GLCode='intlas'  group by GLCode,AccountID 
)b
on a.AccountID = b.AccountID order by AccountID

我可以通过哪些其他方式获得相同的结果?哪一个最好,为什么?我希望没有PIVOT我能做到这一点.



1> Akshey Bhat..:
select AccountId,
       Sum(case when GlCode = 'INTRAC' then amt else 0 end ) as intractamt,
       Sum(case when GlCode = 'INTLAS' then amt else 0 end ) as intlasAmt 
from tbl_LEDGER
group by AccountId 

另一种做同样的方法如上所述.

推荐阅读
ar_wen2402851455
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有