5

我有一个看起来像 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 

例如,我有 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

4 回答 4

5

只需insert_dateGROUP 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
于 2012-09-19T11:51:19.160 回答
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               |
+-------------+-------------+-----------------+
于 2012-09-19T11:52:24.417 回答
0

如果您只需要知道特定creative_id和的最大日期是多少creative_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
于 2012-09-19T11:57:50.617 回答
0

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

当您使用 max(an expression) 时,表达式不应出现在 group by 子句中。

GROUP BY insert_date, creative_id, creative_object

希望这可以帮助。

于 2012-09-19T13:09:09.877 回答