Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

sql-server

I have a table that contains 10 million rows, like this:

enter image description here

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:

enter image description here

How can I solve this?

like image 533
Luan Tran Avatar asked Dec 07 '25 17:12

Luan Tran


2 Answers

When you use aggregates in the select clause, every field that is not aggregated needs to be in the 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]
like image 183
kaineub Avatar answered Dec 10 '25 11:12

kaineub


If you just want column CreatedAt and MAX(CreatedAt) in that case you can do like following.

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.

 SELECT *, 
     (SELECT  MAX([CreatedAt]) 
        FROM [dbo].[CoinData] CDI WHERE CDI.CoinNameID=CD.CoinNameID) AS MAX_CreatedAt
    FROM [dbo].[CoinData] CD
like image 36
PSK Avatar answered Dec 10 '25 11:12

PSK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!