简体   繁体   English

SQL查询 - 如何按列值获取每个组的列的最大值

[英]SQL query - How to get max value of a column of each group by column value

I have a table that contains 10 million rows, like this: 我有一个包含1000万行的表,如下所示:

在此输入图像描述

I want to group by [CoinNameId] (this column is a foreign key) and get max value of [CreatedAt] for each [CoinNameId] group, but my query returns an error: 我想按[CoinNameId]分组(此列是外键)并为每个[CoinNameId]组获取[CreatedAt]的最大值,但我的查询返回错误:

在此输入图像描述

How can I solve this? 我怎么解决这个问题?

When you use aggregates in the select clause, every field that is not aggregated needs to be in the group by. 在select子句中使用聚合时,每个未聚合的字段都需要在group by中。 That's why you are getting an error. 这就是你收到错误的原因。 I'm not sure why you had select * in your query. 我不确定你为什么在查询中选择*。

You'd have to have a query like this: 您必须有这样的查询:

SELECT CoinNameID, max([CreatedAt])
FROM [dbo].[CoinData]
GROUP BY [CoinNameID]

If you just want column CreatedAt and MAX(CreatedAt) in that case you can do like following. 如果您只想要列CreatedAtMAX(CreatedAt) ,那么您可以执行以下操作。

SELECT CoinNameID, MAX([CreatedAt])
FROM [dbo].[CoinData]
GROUP BY [CoinNameID]

In case if you want all columns along with the MAX([CreatedAt]) , you can get it like following. 如果你想要所有列和MAX([CreatedAt]) ,你可以像下面这样得到它。

 SELECT *, 
     (SELECT  MAX([CreatedAt]) 
        FROM [dbo].[CoinData] CDI WHERE CDI.CoinNameID=CD.CoinNameID) AS MAX_CreatedAt
    FROM [dbo].[CoinData] CD

You have select * on your query 您已在查询中select *

SELECT
     CoinNameId,MAX(CreatedAt) AS MaxCreatedAt
     FROM [dbo].[CoinData]
     GROUP BY CoinNameId

This will return MAX(CreatedAt) with other columns 这将返回MAX(CreatedAt)与其他列

 SELECT
    *, MAX([CreatedAt]) OVER (PARTITION BY [CoinNameId])
FROM [dbo].[CoinData]

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

相关问题 在 SQL/Athena 中通过一组列获取最大值 - Get max value by a group of column in SQL/Athena 如何创建SQL查询以获取另一列的每个GROUP'ed BY值的列的唯一值 - How to create SQL query to get unique values of column for each GROUP'ed BY value of another column SQL查询以获取与基于group by的列的最大值对应的另一列的值 - SQL query to get value of another column corresponding to a max value of a column based on group by 使用 SQL 服务器在 SQL 查询的结果中获取每个组中特定列的总和和特定列的最后一个值 - Get the summation a specific column and a last value of a specific column in each group in a result of SQL query using SQL Server 根据多列从每个组中获取具有最大值的行 - Get row with max value from each group based on multiple column 按组的SQL值与最大列值的比率 - SQL ratio of value to max column value by group SQL查询以获取与另一列的MAX值对应的列值? - SQL Query to get column values that correspond with MAX value of another column? 获取查询列的最大值 - Get max value of an query column SELECT 各组按列的最大值 - SELECT max value of each group by column SQL-总和(第1列+第2列+第3列),然后在每个组中选择总和的最大值 - SQL - sum (column 1 + column2 + column3 ) and select max value of sum in each group
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM