简体   繁体   English

在 SQL 如何使用最大列值过滤查询结果

[英]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.在这种情况下,即 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.我可以使用简单的 select max(date) 提取该时间戳,但我不能在 where 子句中使用 max(date) 来过滤数据。

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.一种方法是对 max(date) 进行第一个查询,然后在第二个查询中使用它,然后我可以在 where 子句中使用最大日期,尽管我想在单个查询中执行此操作。 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 子查询中的最大时间戳。

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. 是一个 db<>fiddle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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