从sql中的当前时间戳中选择最后一个和接下来的五个
我有一个带有(order_id,时间戳)的表。时间戳代表订单交付日期,该日期可能在将来发生。如何使用一个 select 语句获取现在的最后 5 个订单和接下来的 5 个订单?是否可以在不使用联合查询的情况下在 sql 中做到这一点?像这样,但没有工会:
select * from table where timestamp <= current_timestamp
order by timestamp desc limit 5
union
select * from table where timestamp >= current_timestamp
order by timestamp asc limit 5
I have a table with (order_id, timestamp). The timestamps represents the orders delivery date, which may occur in the future. How can i get the last 5 orders from now and the next 5 orders from now using one select statement? It it possible to do that in sql without using a union query? Something like this, but without the union:
select * from table where timestamp <= current_timestamp
order by timestamp desc limit 5
union
select * from table where timestamp >= current_timestamp
order by timestamp asc limit 5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为我们可以使用 窗口函数 来做到这一点:
注意我已经任意决定,如果时间戳完全匹配,它将位于未来的行中。您的原始查询将其放入两个组中(但随后 UNION 会消除它),因此如果时间戳完全匹配,您的查询将返回 9 行而不是 10 行。
I think we can do this with a window function:
Note I've arbitrarily decided that if the timestamp exactly matches, it will be in just the future rows. Your original query puts it in both groups (but then the UNION would eliminate it), so if a timestamp exactly matches, your query would return 9 rows instead of 10.
我不认为联合是一个坏主意,但您的查询必须得到解决。您需要将查询嵌入到子查询中才能使用 order by 和 limit。
(未在 PostgreSQL 中测试)。
I don't think a union is such a bad idea but your query must be fixed. You need to embed your queries in sub-queries to be able to use order by and limit.
(Not tested in PostgreSQL).
SQL Server 提供了 TOP 选项。以下是一些示例
在 WWW 中的快速搜索告诉我,在 Oracle 中没有直接等效的内容。您只能使用 rownum 。正如您所知, rownum 在排序之前分配,您可能无法得到实际结果。这是解决方法
SQL Server provides an option in terms of TOP. Here are some examples
A quick search in WWW told me that there is no direct equivalent for this in Oracle. You are left with using rownum. As you know rownum is assigned before sorting you may not get actual result. Here is the workaround