mysql排序组按总计和名称不起作用

时间:2014-10-27 19:56:33

标签: mysql

我有Php程序,输出名称,其中包含相应的参加活动以及每个活动在一段时间内参加的次数。作为输出的一个例子

Name | Run | Swim | Bike | Total

John    3     2      5      10

MySQL查询看起来像这样:

$sql = 'SELECT 
            e.name as Leader,                                       
            SUM(CASE WHEN c.catid = 26 THEN 1 ELSE null END) as "Swim",
            SUM(CASE WHEN c.catid = 25 THEN 1 ELSE null END) as "Bike",
            SUM(CASE WHEN c.catid = 24 THEN 1 ELSE null END) as "Run",
            COUNT("Swim"+"Bike"+"Run") as total
        FROM 
            events as e   
        LEFT JOIN event_categories as c ON c.uid = e.uid
        WHERE 
            (DATE(e.event_start) BETWEEN "'.$from_date.'" and "'.$to_date.'") 
        GROUP BY Leader WITH ROLLUP;';

这很好,但是,如果我想按降序对数据进行排序,那么如果我用以下内容替换最后一个GROUP BY行,我就得不到输出:

  GROUP BY total DESC, Leader WITH ROLLUP;';

这样我就可以获得一个名称总数最低的列表,并且按字母顺序列出总数相同的人。我做错了什么?

2 个答案:

答案 0 :(得分:0)

你不想要GROUP BY Total你只想要总计ORDER BY。 所以查询的最后两行应该是

 GROUP BY Leader WITH ROLLUP
 ORDER BY total DESC

答案 1 :(得分:0)

正如评论中所述,ORDER BYROLLUP不能一起使用。它在这里(http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html)在页面的一半左右说明了这一点。要解决这个问题,您必须在另一个查询中执行ORDER BY,其中您的原始查询充当子查询:

SELECT *
FROM
    (
        SELECT 
            e.name as Leader,                                       
            SUM(CASE WHEN c.catid = 26 THEN 1 ELSE null END) as "Swim",
            SUM(CASE WHEN c.catid = 25 THEN 1 ELSE null END) as "Bike",
            SUM(CASE WHEN c.catid = 24 THEN 1 ELSE null END) as "Run",
            COUNT("Swim"+"Bike"+"Run") as total
        FROM 
            events as e   
        LEFT JOIN event_categories as c ON c.uid = e.uid
        WHERE 
            (DATE(e.event_start) BETWEEN "'.$from_date.'" and "'.$to_date.'") 
        GROUP BY Leader WITH ROLLUP     
    ) as rolldup
ORDER BY Total DESC




ORIGINAL(WRONG)ANSWER:

您没有将Sorts放入GROUP BY子句中。你把它们放在你的ORDER BY条款中:

$sql = 'SELECT 
        e.name as Leader,                                       
        SUM(CASE WHEN c.catid = 26 THEN 1 ELSE null END) as "Swim",
        SUM(CASE WHEN c.catid = 25 THEN 1 ELSE null END) as "Bike",
        SUM(CASE WHEN c.catid = 24 THEN 1 ELSE null END) as "Run",
        COUNT("Swim"+"Bike"+"Run") as total
    FROM 
        events as e   
    LEFT JOIN event_categories as c ON c.uid = e.uid
    WHERE 
        (DATE(e.event_start) BETWEEN "'.$from_date.'" and "'.$to_date.'") 
    GROUP BY Leader WITH ROLLUP
    ORDER BY total DESC;';