表a: 表b:
id 产品名 销售 id 产品名 销售
1 aaa 5 1 aaa 3
2 bbb 4 2 eee 6
3 ccc 6 3 fff 3
4 ddd 3 4 hhh 6
希望实现的结果是
id 产品名 销售
1 aaa 8
2 bbb 4
3 ccc 6
4 ddd 3
5 eee 6
6 fff 3
7 hhh 6
答案:
select
(select count(*)
from
(SELECT 产品名 FROM A union SELECT 产品名 FROM B )
where 产品名<=T.产品名) as ID,
产品名,
sum(销售) as 销售合计
from (
SELECT * FROM A
union all
SELECT * FROM B ) T
group by 产品名
order by 产品名