我有两张桌子:
Customers (name, address, postcode (FK))
Postcodes (postcode (PK), county)
我想知道每个县有多少客户。
我假设我需要在邮政编码上使用内部联接,但不知道如何将其与count(customer_id)
和distinct(county)
结合使用。
答案 0 :(得分:0)
只需将Customers表加入公共字段'postcode'上的Postcodes表即可。然后,您可以使用Group By
获取计数,并按County
SELECT
County,
COUNT(Customer_Id) CustomerCount
FROM
Postcodes pc
JOIN Customers c ON pc.PostalCode = c.PostalCode
GROUP BY
County
答案 1 :(得分:0)
虽然您可以使用SELECT DISTINCT country
编写查询,但它会阻止您执行COUNT
等聚合。相反,您可以使用GROUP BY
,其效果与DISTINCT
大致相同,但功能和灵活性更强。
这两个查询会给出相同的结果,但第二个查询会让您继续添加JOIN
和COUNT
语句。
SELECT DISTINCT county FROM postcodes
SELECT county FROM postcodes GROUP BY county
总的来说,不要使用SELECT DISTINCT
,但要使用这种模式......
SELECT
postcodes.county,
COUNT(customers.customer_id)
FROM
postcodes
INNER JOIN
customers
ON customers.postcode = postcodes.postcode
GROUP BY
postcodes.county