Sql查询帮助初学者

时间:2011-10-26 11:50:33

标签: sql

您好我需要一个查询帮助(是的,我一直在尝试搜索,但找不到帮助我的东西)

我有两张桌子:

客户

  • CustomerID
  • CountryID

国家

  • CountryID
  • Country

我如何编写查询以获得如下结果:

CountryID, Country, NumberOfOccurancesOfThisCountryInTheCustomerTable

非常感谢帮助!

2 个答案:

答案 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 JOININNER JOIN包含Country个记录为Customer的记录(感谢Mark Ba​​nnister)。

答案 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