序列号、ID、日期、数据、数据、数据等
同一 ID 可以有多行。我想创建一个要在报告中使用的表视图,该视图仅显示每个 ID 的最新条目。它应该显示所有列。
有人可以帮我进行 SQL 选择吗?谢谢。
SELECT *
FROM yourTable AS T1
WHERE NOT EXISTS(
SELECT *
FROM yourTable AS T2
WHERE T2.ID = T1.ID AND T2.Date > T1.Date
)
这是另一个:
SELECT T1.*
FROM yourTable AS T1
LEFT JOIN yourTable AS T2 ON
(
T2.ID = T1.ID
AND T2.Date > T1.Date
)
WHERE T2.ID IS NULL
还有一个:
WITH T AS (
SELECT *, ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Date DESC) AS rn
FROM yourTable
)
SELECT * FROM T WHERE rn = 1
好吧,我有点得意忘形了,这是我要发布的最后一篇(目前):
WITH T AS (
SELECT ID, MAX(Date) AS latest_date
FROM yourTable
GROUP BY ID
)
SELECT yourTable.*
FROM yourTable
JOIN T ON T.ID = yourTable.ID AND T.latest_date = yourTable.Date
相关子查询的一个很好的用途:
CREATE VIEW your_view AS
SELECT *
FROM your_table a
WHERE date = (
SELECT MAX(date)
FROM your_table b
WHERE b.id = a.id
)
您的日期列需要唯一标识每一行(如
TIMESTAMP
类型)。