当涉及到关系数据库时,说“前 N 行”确实是模棱两可的。
我假设您想按“金额”升序排序。
我会添加第二列(到表或视图),如“sum_up_to_here”,并创建类似的内容:
create view mytable_view as
select
mt1.amount,
sum(mt2.amount) as sum_up_to_here
from
mytable mt1
left join mytable mt2 on (mt2.amount < mt1.amount)
group by mt1.amount
或者:
create view mytable_view as
select
mt1.amount,
(select sum(amount) from mytable where amount < mt1.amount)
from mytable mt1
然后我会选择最后的行:
select amount from mytable_view where sum_up_to_here < (some value)
如果您不关心性能,您当然可以在一个查询中运行它:
select amount from
(
select
mt1.amount,
sum(mt2.amount) as sum_up_to_here
from
mytable mt1
left join mytable mt2 on (mt2.amount < mt1.amount)
group by mt1.amount
) t where sum_up_to_here < 20