如何使用max来执行group by子句

时间:2012-09-19 11:46:16

标签: mysql sql

我的查询看起来像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。我有4行: insert_date creative_id,creative_object

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

查询返回所有行。

我需要返回

june13 a b
 june13 c d

如何修改查询?

4 个答案:

答案 0 :(得分:5)

只需从insert_date子句中删除GROUP BY

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

答案 1 :(得分:0)

create table rtb_creatives (insert_date varchar(20), creative_id char(1), creative_object char(1));
insert into rtb_creatives (insert_date, creative_id, creative_object) values
('june 12', 'a', 'b'),
('june 13', 'a', 'b'),
('june 12', 'c', 'd'),
('june 13', 'c', 'd')
;

SELECT insert_date, creative_id, creative_object 
from rtb_creatives 
where 
    adgroup_id='agid1608844879' 
    and is_delete in (0)
    and insert_date = (select max(insert_date) from rtb_creatives)
group by insert_date, creative_id, creative_object
;
+-------------+-------------+-----------------+
| insert_date | creative_id | creative_object |
+-------------+-------------+-----------------+
| june 13     | a           | b               |
| june 13     | c           | d               |
+-------------+-------------+-----------------+

答案 2 :(得分:0)

如果您只需要知道特定creative_idcreative_object的最长日期是什么,您只需要从GROUP BY子句中删除insert_date,这将导致选择最大日期对于每一组,我也会改变IN状态以使其更清楚(尽管在这种特殊情况下它并没有产生很大的不同),就像那样:

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

答案 3 :(得分:0)

这里的问题是您的插入日期被定义为字符串。它应该被定义为日期类型,以便Max()可以计算正确的顺序。假设还有另一个日期,例如8月05日作为插入日期,那么Max将返回6月13日。请记住,在字符串排序中,6月13日和6月13日存在差异。

当你使用max(表达式)时,表达式不应该在group by子句中。

GROUP BY insert_date, creative_id, creative_object

希望这有帮助。