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

时间:2015-12-28 10:37:36

标签: sql sql-server tsql

我有一张表 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我能做到这一点。

3 个答案:

答案 0 :(得分: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 

另一种方法也是如上所述。

答案 1 :(得分:0)

这是我的方法:

 DECLARE @tbl_LEDGER TABLE(AccountId VARCHAR(100),GlCode VARCHAR(100),Amt DECIMAL(8,4));
 INSERT INTO @tbl_LEDGER VALUES
 ('LAS00001','INTRAC',100)
,('LAS00002','INTRAC',150)
,('LAS00001','INTLAS',200);

WITH IntracValues AS
(
    SELECT * 
    FROM @tbl_LEDGER
    WHERE GlCode='INTRAC'
)
,IntlasValues AS
(
    SELECT * 
    FROM @tbl_LEDGER
    WHERE GlCode='INTLAS'
)
SELECT IntracValues.AccountId
      ,ISNULL(IntracValues.Amt,0) AS intractAmt
      ,ISNULL(IntlasValues.Amt,0) AS intlasAmt
FROM IntracValues 
FULL OUTER JOIN IntlasValues ON IntracValues.AccountId=IntlasValues.AccountId

答案 2 :(得分:0)

你能检查一下:

DBCC DROPCLEANBUFFERS;
SET STATISTICS IO ON;

如果您没有对生产进行测试,请执行以下查询:

FLOOR(timestamp / 86400) * 86400

并使用以下site来比较消息标签中的统计信息。