gpt4 book ai didi

mysql 按总数和名称对组进行排序不起作用

转载 作者:行者123 更新时间:2023-11-29 23:30:44 25 4
gpt4 key购买 nike

我有一个 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;';

这样我就可以得到一个列表,其中包含总分最高到最低的姓名,总分相同的人按字母顺序列出。我做错了什么?

最佳答案

正如评论中提到的,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




原始(错误)答案:

您不能将排序放入 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;';

关于mysql 按总数和名称对组进行排序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26595779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com