在查询中使用MYSQL条件语句和变量

时间:2010-11-16 12:26:18

标签: mysql conditional-statements

嗨,似乎无法在之后构建MYSQL查询。

假设我有两列结果:1)浏览器名称和2)浏览器计数。

如果它变得复杂,我希望一旦达到总计数的90%,将所有其他浏览器重命名为其他浏览器,并相应地标记左边的百分比。

我知道在开始主声明之前我可以将总计数作为变量:

SELECT @total := COUNT(id) FROM browser_table WHERE start LIKE "2010%";

然后我可以通过浏览器对结果进行分组:

SELECT browser, COUNT(id) AS visits
FROM browser_table
WHERE start LIKE "2010%"
GROUP BY browser

我知道我需要在一个case语句(和一个计数器变量)中对列进行排序,但不确定如何在上面的查询中实现:

CASE 
  WHEN counter >= 0.9* @total THEN 'other'
  ELSE browser
END AS browser;

希望有道理吗?谢谢你的时间....

1 个答案:

答案 0 :(得分:0)

这是一种方法......

您可以根据this answer计算出运行总计。例如:

SET @rt := 0;
SELECT
    browser,
    visits,
    (@rt := @rt + visits) AS running_total
FROM
    (
        SELECT
            browser,
            COUNT(id) AS visits
        FROM
            browser_table
        WHERE
            start LIKE '2010%'
        GROUP BY
            browser
        ORDER BY
            visits DESC
    ) AS sq
;


一旦你有了这个,你可以在此基础上创建一个'其他'类别:

SET @threshold := (SELECT COUNT(id) FROM browser_table WHERE start LIKE '2010%') * 0.90;
SET @rt := 0;
SELECT
    browser,
    SUM(visits) AS total_visits
FROM
    (
        SELECT
            IF (@rt < @threshold, browser, 'Other') AS browser,
            visits,
            (@rt := @rt + visits) AS running_total
        FROM
            (
                SELECT
                    browser,
                    COUNT(id) AS visits
                FROM
                    browser_table
                WHERE
                    start LIKE '2010%'
                GROUP BY
                    browser
            ) AS sq1
        ORDER BY
            visits DESC
    ) AS sq2
GROUP BY
    browser
ORDER BY
    total_visits DESC
;