sql查询金额总和

问题描述 投票:0回答:2

我需要列表中 catid 的金额总和 (11, 12, 13, 14, 15, 15) if (catid>0 and catid<10) exists in receipt.

catid   amount      receiptno
1       2,00        1
12      3,00        1
13      4,00        1
1       2,00        2
1       2,00        3
13      4,00        3
12      3,00        4
13      4,00        4

结果应该是

catid   sum
12      3,00
13      8,00

我尝试过一些方法,但是这样的 SQL 太慢了

select catid, sum(amount)
from mytable
where receiptno in (select distinct(receiptno) from mytable where catid>0 and catid<10) 
and catid in (11, 12, 13, 14, 15, 16)
group by catid
sql query-optimization firebird
2个回答
0
投票

我建议使用

inner join
而不是子查询 :

select catid, sum(amount)
from mytable t
inner join (
  select distinct(receiptno) 
  from mytable 
  where catid>0 and catid<10
) as s on s.receiptno = t.receiptno
and catid in (11, 12, 13, 14, 15, 15)
group by catid

添加此索引可能会有所帮助:

CREATE INDEX mytable_catid_idx ON mytable (catid);

0
投票

更好的是,您可以在从子查询中删除“distinct”后尝试相同的查询。

select catid, sum(amount)
from mytable
where receiptno in (select receiptno from mytable where catid>0 and catid<10) 
and catid in (11, 12, 13, 14, 15, 15)
group by catid
© www.soinside.com 2019 - 2024. All rights reserved.