例如,我有以下数据库条目:
timestamp | value1 | value 2
----------
1452|5|7
1452|1|6
1452|2|7
1623|1|2
1623|5|6
1623|4|5
1623|4|7
1855|1|2
现在我想要一个sql查询,它只返回值为最大的时间戳的value1。因此它应该只返回时间戳1623及其值。 我第一次考虑计数,但这只会返回可用性的数量,而不是条目。
答案 0 :(得分:2)
select *
from T
inner join (select timestamp
from T
group by timestamp
order by count(*) desc
limit 1) t2
on T.timestamp = t2.timestamp
答案 1 :(得分:0)
WITH CTE AS (
SELECT *, COUNT(timestamps) OVER (PARTITION BY value1, timestamps) AS cnt
FROM mytable
), cte2 as (select *, row_number() over (partition by value1 order by cnt DESC, timestamps) as Rn FROM cte)
SELECT value1, timestamps , cnt FROM CTE2 WHERE Rn = 1;