postgresql提取到每个组的最后一行
我有以下数据
应用程序 | 人 | 登录 |
---|---|---|
Slack | Jenny | 2019-01-01 |
Slack | Jenny | 2020-01-01 |
Slack | Jenny | 2021-01-01 |
Slack | Yang | 2020-06-06 |
Slack | Yang Yang | 2021-06-06 |
,用于每个组应用程序和用户,用户,用户,用户,我需要获取最新的登录日期。我试图使用窗口功能,但无法获得我期望的结果:
SELECT app, people, LAST_VALUE(login) OVER (PARTITION BY app, people ORDER BY login)
FROM xxxxx
有什么建议吗?
I have the following data
app | people | login |
---|---|---|
slack | Jenny | 2019-01-01 |
slack | Jenny | 2020-01-01 |
slack | Jenny | 2021-01-01 |
slack | Yang | 2020-06-01 |
slack | Yang | 2021-06-01 |
For each group app and user, I need to get the latest login date. I tried to use a window function, but could not get the result of what I am expecting:
SELECT app, people, LAST_VALUE(login) OVER (PARTITION BY app, people ORDER BY login)
FROM xxxxx
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,从组中的最后一个值不需要窗口函数,只需选择不同的选择即可。我假设每个{appp,people}对必须仅在结果中显示一次。
391236DA9E56CF01A44444444444445B2C9159
”命令在窗口函数中使用,然后以“运行总和”模式运行窗口函数,仅了解已在分区内处理过的行。如果我们想从整个分区获取信息,那么我们必须明确指出。
在这种情况下,使用
max
看起来更好的选择(如@lemon指向)To get first, last value from group there is no need for window function, just distinct select. I've assumed that each {appp, people} pair must be presented only once in results.
DB Fiddle
And example with
LAST_VALUE
When
ORDER BY
is used inside window function then window function run in "running sum" mode, knowing only about rows already processed inside partition. If we want to get information from whole partition then we must explicitly point that.In this case, using
MAX
looks like better choice (as @lemon pointed)您可以使用
max
窗口函数代替last_value
窗口函数:检查demo 在这里。
相反,如果要汇总您的“ app ”和“ people ”值,上次登录值,也可以使用
max
contregation功能:检查演示在这里。
You can use the
MAX
window function in place of theLAST_VALUE
window function:Check the demo here.
Instead, if you want to aggregate your "app" and "people" values on the last login value, you can also use the
MAX
aggregation function:Check the demo here.