表基本上看起来像:
序列号,ID,日期,数据,数据,数据等
相同ID可以有多行。我想创建一个在Reports中使用的表的视图,它只显示每个ID的最新条目。它应该显示所有列。
有人可以帮我解决SQL选择吗?感谢。
答案 0 :(得分:15)
有大约5种不同的方法可以做到这一点,但这里有一个:
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
答案 1 :(得分:0)
这似乎是correlated subqueries的好用:
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
类型)。
答案 2 :(得分:0)
我会使用DISTINCT ON
CREATE VIEW your_view AS
SELECT DISTINCT ON (id) *
FROM your_table a
ORDER BY id, date DESC;
之所以有用,是因为distinct on
禁止使用括号中的表达式重复的行。 DESC
中的order by
表示通常排在最后的那个将是第一个,因此将在结果中显示一个。
https://www.postgresql.org/docs/10/static/sql-select.html#SQL-DISTINCT