我有一个表(order_id,时间戳)。时间戳表示订单交货日期,这可能发生在未来。我如何使用一个选择语句从现在开始获取最后 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
最佳答案
我认为我们可以用 window function 来做到这一点:
WITH Numbered AS (
SELECT
*, --TODO, pick columns
ROW_NUMBER() OVER (ORDER BY CASE WHEN timestamp < current_timestamp THEN timestamp ELSE '18000101' END desc) as HistoricRN,
ROW_NUMBER() OVER (ORDER BY CASE WHEN timestamp >= current_timestamp THEN timestamp ELSE '99991231' END) as FutureRN
FROM table
)
SELECT
* --TODO, pick columns
from Numbered
where HistoricRN between 1 and 5 or FutureRN between 1 and 5
请注意,我已经武断地决定,如果时间戳完全匹配,它将出现在未来的行中。您的原始查询将它放在两个组中(但 UNION 会消除它),因此如果时间戳完全匹配,您的查询将返回 9 行而不是 10 行。
关于sql - 从sql中的当前时间戳中选择最后一个和接下来的五个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5646833/