MySQL GROUP BY ...排除其他字段中的值

时间:2017-08-20 21:50:03

标签: mysql sql group-by

我的统计页面的MySQL查询有问题。我想使用类似于以下内容的查询将所有行检索到" version "但我想在其他字段中排除值" platform "如果不是相同的值。

示例值:

| platform | version | ...
----------------------
| Windows  | 1.0.1   |
| Windows  | 1.0.1   |
| Windows  | 1.0.1   |
| Windows  | 1.0.2   |
| Windows  | 1.0.3   |
| Linux    | 1.0.1   |
| Linux    | 1.0.1   |
| Linux    | 1.0.2   |
| Mac      | 1.0.1   |
| Mac      | 1.0.1   |

查询:

SELECT
    platform,
    version,
    COUNT(*) AS count
FROM
    user
GROUP BY
    version

结果:

| platform | version | count |
------------------------------
| Windows  | 1.0.1   | 7     |
| Windows  | 1.0.2   | 2     |
| Windows  | 1.0.3   | 1     |

我需要以下结果:

| platform | version | count |
------------------------------
| Windows  | 1.0.1   | 3     |
| Windows  | 1.0.2   | 1     |
| Windows  | 1.0.3   | 1     |
| Linux    | 1.0.1   | 2     |
| Linux    | 1.0.2   | 1     |
| Mac      | 1.0.1   | 2     |

我希望你能帮助我......对不起我的英语。

1 个答案:

答案 0 :(得分:2)

我认为你只需要正确的group by条款:

SELECT platform, version, COUNT(*) AS count
FROM user
GROUP BY platform, version;

您的查询实际上并不是语法正确的SQL。 platform列位于SELECT,但不在GROUP BY中。几乎所有MySQL以外的数据库都会正确返回错误。