我需要列表中 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
我建议使用
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);
更好的是,您可以在从子查询中删除“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