[英]How can this sql grouped query be corrected? (I think this is sql generic, we use postgresql)
数据集示例如下:
noteid seq notebalance 1 4 125.00 1 3 120.00 2 8 235.00 2 6 235.00 2 5 200.00 3 9 145.00 4 17 550.00 4 16 550.00 4 14 500.00 4 12 450.00 4 10 400.00 ...
因此我们基本上在每个noteid组的开头都有最新的notebalance。
什么是正确的SQL语法,以获得每个noteid的最新余额?
如:
1 4 125.00 2 8 235.00 3 9 145.00 4 17 550.00
通用(= ANSI SQL)解决方案是使用窗口函数:
select noteid, seq, notebalance
from (
select noteid, seq, notebalance,
row_number() over (partition by noteid order by seq desc) as rn
from the_table
) t
where rn = 1
order by noteid;
当使用Postgres时,通常使用distinct on
运算符更快:
select distinct on (noteid) noteid, seq, notebalance
from the_table
order by noteid, seq desc;
SQLFiddle示例: http ://sqlfiddle.com/#!15/8ca27/2
我认为ROW_NUMBER()是您要寻找的。 这类似于该SO问题 。
“ seq最高的记录”:=“没有更高的seq记录(对于此noteid
)”
SELECT noteid, seq, notebalance
FROM the_table tt
WHERE NOT EXISTS (
SELECT * FROM the_table nx
WHERE nx.noteid = tt.noteid
AND nc.seq > tt.seq
)
ORDER BY noteid
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.