简体   繁体   中英

In SQL how to use a max column value to filter query results

在此处输入图像描述

I want to group this data by Description-Name pairs and return how many entries with a given Description-Name pair had in the data.

Additionally, I want to filter out all entries that are not from the most recent (max) timestamp. In this case that is 2021-02-15 19:00:00.000.

I am able to extract that timestamp with a simple select max(date), but I cannot use max(date) in a where clause to filter the data.

One approach would be to the first query for the max(date) and then use that in a second query where I can then use the max date in a where clause, though I want to do it in a single query. Would greatly appreciate advice and I'd be glad to clarify anything.

One possibility is to select the maximum timestamp in a sub-query.

select description, name, count(*)
from data
where timestamp = (select max(timestamp) from data)
group by description, name
order by description, name;

Here is a db<>fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM