我有一张桌子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我能做到这一点.
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
另一种做同样的方法如上所述.