[英]How to get first and last row using redshift?
I have this table in redshift我有这张桌子在红移
no date_status date_ant status row_ant
1 11 Jan 2023, 07.00 11 Jan 2023, 07.00 ANT 1
1 11 Jan 2023, 09.00 11 Jan 2023, 10.00 AU 2
1 12 Jan 2023, 12.00 12 Jan 2023, 12.00 DLV 3
2 14 Jan 2023, 09.00 14 Jan 2023, 09.00 ANT 1
2 14 Jan 2023, 10.00 14 Jan 2023, 10.00 AU 2
2 15 Jan 2023, 10.00 15 Jan 2023, 14.00 ANT 3
I want to write a query which supposed to get the first and last row based date_status
and also row_ant
for each no
我想编写一个查询,该查询应该获取基于
date_status
的第一行和最后一行以及每个no
的row_ant
I want to get the date_ant where the status = ANT and row_ant = 1
, while for the last row I want to get maximum date_status and the status column whatever the value is我想获取
date_ant where the status = ANT and row_ant = 1
,而对于最后一行,我想获取最大 date_status 和状态列,无论值是什么
The desired result would be something like this:期望的结果将是这样的:
no date_ant first_status date_last_status last_status
1 11 Jan 2023, 07.00 ANT 12 Jan 2023, 12.00 DLV
2 14 Jan 2023, 09.00 ANT 15 Jan 2023, 10.00 ANT
how can I get the desired result above with a query in redshift?如何通过 redshift 中的查询获得上面想要的结果? I supposed it can use row partition by, but I am not exactly sure how to get the correct table.
我认为它可以使用行分区依据,但我不确定如何获得正确的表。
Any help would be much appreciated.任何帮助将非常感激。 Thank you in advance
先感谢您
We can use ROW_NUMBER()
here, twice :我们可以在这里使用
ROW_NUMBER()
两次:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY date_ant) rn1,
ROW_NUMBER() OVER (ORDER BY date_ant DESC) rn2
FROM yourTable
WHERE status = 'ANT' AND row_ant = 1
)
SELECT no, date_status, date_ant, status, row_ant
FROM cte
WHERE rn1 = 1 OR rn2 = 1
ORDER BY date_status;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.