您好我需要一个查询帮助(是的,我一直在尝试搜索,但找不到帮助我的东西)
我有两张桌子:
客户
CustomerID
CountryID
国家
CountryID
Country
我如何编写查询以获得如下结果:
CountryID, Country, NumberOfOccurancesOfThisCountryInTheCustomerTable
非常感谢帮助!
答案 0 :(得分:6)
试试这个:
SELECT CountryID, Country,
COUNT(Customer.CustomerID) AS NumberOfOccurancesOfThisCountryInTheCustomerTable
FROM Country LEFT JOIN
Customer ON Country.CountryID = Customer.CountryID
GROUP BY Country.CountryID, Country.Country
编辑:使用LEFT JOIN
与INNER JOIN
包含Country
个记录为Customer
的记录(感谢Mark Bannister)。
答案 1 :(得分:2)
这样的事情应该这样做,假设CustomerId是主键:
SELECT
Country.CountryId,
Country.Country,
COUNT(Customers.CustomerId)
FROM
Country INNER JOIN Customers ON Country.CountryId = Customers.CountryId
GROUP BY
CountryId, Country