选择不同的,在行尾显示计数

时间:2012-02-08 11:53:18

标签: mysql select count distinct

我有这个表/数据结构:

ID    Area       Postcode
------------------------
1     "Area 1"   "EN1 1NE"
2     "Area 2"   "AB2 3BA"
3     "Area 1"   "EN1 1NE"
4     "Area 3"   "XY4 5ZA"
5     "Area 4"   "MN6 5OP"

第1行和第3行有重复的邮政编码和区域。我需要一个输出如下计数的查询:

Area       Postcode    Count
----------------------------
"Area 1"   "EN1 1NE"   2
"Area 2"   "AB2 3BA"   1
"Area 3"   "XY4 5ZA"   1
"Area 4"   "MN6 5OP"   1

我用DISTINCT和/或COUNT和/或子查询进行了搜索和播放,但在这里真的输了! #弱-SQL福

谢谢! 本

2 个答案:

答案 0 :(得分:3)

您可以将count(*)与group by一起使用:

select Area, Postcode, count(*) from TABLE group by Area, Postcode;

答案 1 :(得分:2)

必须在ALIAS COUNT内使用反引号来转义保留字。

SELECT Area, 
       Postcode, 
       COUNT(ID) as `Count` 
FROM   tableName 
Group BY Area, Postcode
ORDER BY Area;
相关问题