使用GROUP BY将两列分组

时间:2011-08-24 20:31:46

标签: mysql sql

我有以下查询,它会生成一个表。

SELECT c.name AS campaign
  , c.traffic_source
  , ic.keyword
  , COUNT(ic.keyword) AS keycount
  , SUM(ls.amount) AS total_amount
  , ls.buyer AS buyers
  , ic.create_date AS 'date'
FROM in_clicks AS ic 
INNER JOIN ads AS a ON (ic.ad_id = a.id)
INNER JOIN ad_groups AS ag ON (a.ad_group_id = ag.id)
INNER JOIN campaigns AS c ON (ag.campaign_id = c.id)
INNER JOIN leads AS l ON (ic.id = l.in_click_id)
INNER JOIN lead_status AS ls ON (l.id = ls.lead_id)
WHERE keyword IS NOT NULL AND ic.create_date BETWEEN '2011-08-21' AND '2011-08-22'
      AND ic.location NOT LIKE 'Littleton%' AND ls.discriminator = 'AUTO_POST'
GROUP BY ic.keyword
ORDER BY keycount DESC

此查询生成(缩写):

campaign             count    
Auto                 10
Auto Branded         8
Auto California      7 
Auto Branded         6
Auto                 2
Auto                 2 
Auto California      1

我想要做的是根据“计数”和广告系列名称对数据进行分组。 所以它看起来像:

   campaign             count    
    Auto                 10
    Auto                 2
    Auto                 2 
    Auto Branded         8
    Auto Branded         6
    Auto California      7 
    Auto California      1

如何将广告系列和计数组合在一起?

2 个答案:

答案 0 :(得分:3)

看起来你真的想要订购,而不是分组,所以只需按顺序添加campaign,即

ORDER BY campaign, keycount DESC

答案 1 :(得分:2)

您只想更改输出顺序,因此您应该在最后一行按广告系列排序:

ORDER BY campaign ASC, keycount DESC