MySQL Group按邮政编码

时间:2012-02-24 22:00:14

标签: mysql group-by zipcode

我有一张包含订阅信息的表。一些邮件邮政编码是五位数,而有些是9(55025对55025-4056)。我想运行一个查询来计算每个邮政编码中的总订阅数,但需要将9位数的邮政编码与其匹配的5位数字进行分组。

SELECT zip, COUNT(id) AS total FROM subscriptions WHERE status = 'A' GROUP BY zip

但显然它将55025和55025-4056视为两个不同的邮政编码。如果55025有100条记录而55025-4056有10条记录,我希望结果显示55025 = 110条记录。如何执行此查询以按邮政编码的前5位分组?

由于

3 个答案:

答案 0 :(得分:4)

SELECT LEFT(zip,5) zip, COUNT(id) AS total
FROM subscriptions WHERE status = 'A'
GROUP BY LEFT(zip,5); 

答案 1 :(得分:0)

SELECT zip, COUNT(id) AS total 
FROM subscriptions 
WHERE status = 'A' 
GROUP BY SUBSTRING(zip, 1, 5)

答案 2 :(得分:0)

你可以GROUP BY表达式,选择你最喜欢的字符串函数来完成工作 http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

SELECT zip, COUNT(id) AS total FROM subscriptions
WHERE status = 'A'
GROUP BY LEFT( zip, 5 );