Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a group by clause with a max

Tags:

sql

mysql

I have a query that looks like thos :

SELECT max(insert_date),
       creative_id,
       creative_object
FROM   rtb_creatives
WHERE  adgroup_id = 'agid1608844879'
       AND is_delete IN ( 0 )
GROUP  BY insert_date,
          creative_id,
          creative_object 

E.g. I have 4 rows: insert_date creative_id, creative_object

 june 12 a b
 june13 a b
 june 12 c d
 june13 c d

The query is returning all rows.

I need to return

june13 a b
 june13 c d

How do I modify the query?

like image 912
Tampa Avatar asked Sep 19 '12 11:09

Tampa


People also ask

Can we use MAX function in GROUP BY clause?

Max() function with Group by In this page we are discussing, how the GROUP BY clause along with the SQL MAX() can be used to find the maximum value of a column over each group.

Does Max need GROUP BY?

Expressions that are not encapsulated within the MAX function and must be included in the GROUP BY clause at the end of the SQL statement. This is the column or expression from which the maximum value will be returned.

Does Max in SQL require GROUP BY?

Using MIN() and MAX() in the Same Query You can use both the MIN and MAX functions in one SELECT . If you use only these functions without any columns, you don't need a GROUP BY clause.

How do I sort by highest number in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.


1 Answers

Just remove the insert_date from the GROUP BY clause:

SELECT max(insert_date) AS insert_date, creative_id, creative_object
from rtb_creatives 
where adgroup_id='agid1608844879' and is_delete in (0)
group by creative_id, creative_object
like image 188
Mahmoud Gamal Avatar answered Oct 29 '22 18:10

Mahmoud Gamal