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

Sam*_*ack 2 sql t-sql sql-server

我有一张桌子tbl_LEDGER

+-----------+--------+-----+
| AccountId | GlCode | Amt |
+-----------+--------+-----+
| LAS00001  | INTRAC | 100 |
| LAS00002  | INTRAC | 150 |
| LAS00001  | INTLAS | 200 |
+-----------+--------+-----+
Run Code Online (Sandbox Code Playgroud)

期望的结果:

+-----------+------------+-----------+
| AccountId | intractamt | intlasAmt |
+-----------+------------+-----------+
| LAS00001  |        100 |       200 |
| LAS00002  |        150 |         0 |
+-----------+------------+-----------+
Run Code Online (Sandbox Code Playgroud)

这是我的工作查询:

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
Run Code Online (Sandbox Code Playgroud)

另一个工作查询:

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
Run Code Online (Sandbox Code Playgroud)

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

Aks*_*hat 5

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 
Run Code Online (Sandbox Code Playgroud)

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