[英]SQL Count total of addresses
Here is my data 这是我的数据
Vehicle | Street | Number | Postcode
Car Fakestreet 3 0010NK
Motorbike Fakestreet 3 0010NK
Car Fakestreet 4 0010NK
Car Fakestreet 1 0010NK
Companycar Fakestreet 1 0010NK
I want to count unique adresses per postcode so this is want I want to see: 我想计算每个邮政编码的唯一地址,所以我想看看:
Postcode | Total_adresses
0010NK | 3
I thought this must be a simple query so I have this: 我认为这一定是一个简单的查询,所以我有这个:
SELECT Postcode, COUNT(*) AS total_adresses
FROM my_database
WHERE Postcode = '0010NK'
GROUP BY Postcode, Street, Number
But I get this result: 但是我得到这个结果:
Postcode | total_adresses
0010NK | 2
0010NK | 2
0010NK | 1
I can't get my head around why it doesn't give me the desired result. 我无法理解为什么它不能给我想要的结果。 Any ideas why? 有什么想法吗?
Just aggregate by the one column: 只需按一列进行汇总:
SELECT Postcode, COUNT(*) AS total_adresses
FROM my_database
WHERE Postcode = '0010NK'
GROUP BY Postcode;
The combination of keys in the GROUP BY
defines each row in the aggregated result set. GROUP BY
的键组合定义了聚合结果集中的每一行 。 You want only one row per Postcode
, so that is the only key you should have in the GROUP BY
. 每个Postcode
只需要一行,因此这是您在GROUP BY
唯一的键。
EDIT: 编辑:
To count the number of distinct addresses, use COUNT(DISTINCT)
. 要计算不同地址的数量,请使用COUNT(DISTINCT)
。 Here is one way: 这是一种方法:
SELECT Postcode, COUNT(DISTINCT CONCAT(STREET, ' ', NUMBER, ' ', POSTALCODE) AS total_adresses
FROM my_database
WHERE Postcode = '0010NK'
GROUP BY Postcode;
Some databases support: 一些数据库支持:
SELECT Postcode, COUNT(DISTINCT STREET, NUMBER, POSTALCODE) AS total_adresses
Have a derived table to return the unique addresses. 有一个派生表以返回唯一地址。 Then GROUP BY its result: 然后按结果分组:
select Postcode, count(*)
from
(
SELECT DISTINCT Street, Number, Postcode
FROM my_database
) dt
group by Postcode
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.