样本输入
Name | Value | Timestamp
-----|-------|-----------------
One | 1 | 2016-01-01 02:00
Two | 3 | 2016-01-01 03:00
One | 2 | 2016-01-02 02:00
Two | 4 | 2016-01-03 04:00
期望的输出
Name | Value | EarliestTimestamp | LatestTimestamp
-----|-------|-------------------|-----------------
One | 2 | 2016-01-01 02:00 | 2016-01-02 02:00
Two | 4 | 2016-01-01 03:00 | 2016-01-03 04:00
尝试查询
I am trying to use ROW_NUMBER()
and PARTITION BY
to get the latest Name
and Value
but I would also like the earliest and latest Timestamp
值:
SELECT
t.Name,
t.Value,
t.????????? AS EarliestTimestamp,
t.Timestamp AS LatestTimestamp
FROM
(SELECT
ROW_NUMBER() OVER (PARTITION BY Name ORDER BY TIMESTAMP DESC) AS RowNumber,
Name,
Value
Timestamp) t
WHERE t.RowNumber = 1
原文由 Muhammad Rehan Saeed 发布,翻译遵循 CC BY-SA 4.0 许可协议
这可以使用窗口函数
min
和max
来完成。例子
编辑:根据评论
编辑:另一种方法是使用
first_value
窗口函数,这将消除对子查询和连接的需要。