过滤GROUP BY结果与另一个GROUP BY减少

时间:2015-12-14 13:14:24

标签: mysql sql group-by

我已经有了一个基本查询来从我的数据库中选择所有位置,然后按照邮政编码的前2个字符对它们进行分组。

SELECT LEFT(`locationPostcode`, 2) as `postcode`, count(`locationPostcode`) as `locationCount`
FROM `locations`
WHERE `locationPostcode` IS NOT NULL
AND `locationPostcode` <> ''
GROUP BY `postcode`
ORDER BY `locationCount` DESC

因为有些邮政编码只以1个字母而不是2开头,所以我需要再次对其进行分组,以使这些邮政编码(例如E1,W2)只显示其首字母。

我的尝试是LEFT('postcode', 2)再次对它们进行分组,但它似乎没有太大影响(查询如下)

SELECT postcode, locationCount FROM (

    SELECT LEFT(`locationPostcode`, 2) as `postcode`, count(`locationPostcode`) as `locationCount`
    FROM `locations`
    WHERE `locationPostcode` IS NOT NULL
    AND `locationPostcode` <> ''
    GROUP BY `postcode`
    ORDER BY `locationCount` DESC
    ) as `outer`
GROUP BY left(`postcode`, 1)
ORDER BY `locationCount` DESC

澄清:我希望我的实际邮政编码结果如下:

postcode | count
----------------
E        | 3000
W        | 2200
SW       | 1300

而不是:

postcode | count
----------------
SW       | 1300
E1       | 1000
E2       | 300
S1       | 200
S2       | 100
S3       | 50

1 个答案:

答案 0 :(得分:2)

您的问题描述建议group by的条件案例:

SELECT (case when substr(locationPostcode, 2, 1) between 'A' and 'Z'
             then left(`locationPostcode`, 2)
             else left(locationPostcode, 1)
        end) as postcode_prefix, count(`locationPostcode`) as `locationCount`
FROM `locations`
WHERE `locationPostcode` IS NOT NULL AND `locationPostcode` <> ''
GROUP BY postcode_prefix
ORDER BY `locationCount` DESC;