从 group by 中获取一条记录,而无需手动键入所有列
Taking one record from group by without manually typing all columns
我有一个 table 以下列:
id, col_1, col_2, col_3, .... col_1000, timestamp
我只想为每个 id 记录一条记录,并采用最新的时间戳。也就是说,我的查询是:
select id, max_by(col_1, timestamp), max_by(col_2, timestamp), max_by(col_3, timestamp), ... max_by(col_1000, timestamp), max_by(timestamp, timestamp) group by id
因为有这么多专栏,我想知道有没有办法可以做这样的事情:
select max_by(*, timestamp) group by id
这样我就不必手动输入所有列了?谢谢!
嗯。 . .您可以使用 row_number()
:
select t.*
from (select t.*,
row_number() over (partition by id order by timestamp desc) as seqnum
from t
) t
where seqnum = 1;
您也可以使用相关子查询或 join
:
来表达这一点
select t.*
from t join
(select id, max(timestamp) as max_timestamp
from t
group by id
) tt
on t.id = tt.id and t.timestamp = tt.max_timestamp
我有一个 table 以下列:
id, col_1, col_2, col_3, .... col_1000, timestamp
我只想为每个 id 记录一条记录,并采用最新的时间戳。也就是说,我的查询是:
select id, max_by(col_1, timestamp), max_by(col_2, timestamp), max_by(col_3, timestamp), ... max_by(col_1000, timestamp), max_by(timestamp, timestamp) group by id
因为有这么多专栏,我想知道有没有办法可以做这样的事情:
select max_by(*, timestamp) group by id
这样我就不必手动输入所有列了?谢谢!
嗯。 . .您可以使用 row_number()
:
select t.*
from (select t.*,
row_number() over (partition by id order by timestamp desc) as seqnum
from t
) t
where seqnum = 1;
您也可以使用相关子查询或 join
:
select t.*
from t join
(select id, max(timestamp) as max_timestamp
from t
group by id
) tt
on t.id = tt.id and t.timestamp = tt.max_timestamp