简体   繁体   English

如何将此sql分组查询更正? (我认为这是sql通用的,我们使用postgresql)

[英]How can this sql grouped query be corrected? (I think this is sql generic, we use postgresql)

Data set example is as follows: 数据集示例如下:

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
...

so we basically have the latest notebalance at the beginning of each noteid group. 因此我们基本上在每个noteid组的开头都有最新的notebalance。

What is the proper sql syntax to obtain the latest balances for each noteid? 什么是正确的SQL语法,以获得每个noteid的最新余额?

as in: 如:

1       4      125.00
2       8      235.00
3       9      145.00
4       17     550.00

A generic (= ANSI SQL) solution would be to use a window function: 通用(= 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;

When using Postgres, it's usually faster to use the distinct on operator: 当使用Postgres时,通常使用distinct on运算符更快:

select distinct on (noteid) noteid, seq, notebalance
from the_table
order by noteid, seq desc;

SQLFiddle example: http://sqlfiddle.com/#!15/8ca27/2 SQLFiddle示例: http ://sqlfiddle.com/#!15/8ca27/2

I think ROW_NUMBER() is what you are looking for. 我认为ROW_NUMBER()是您要寻找的。 This is similar to this SO question . 这类似于该SO问题

"the record with the highest seq" := "there is no record with a higher seq (for this noteid )" “ 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM