Select 个来自多个表的列

Select columns from several tables with count

我在 SQL 服务器中有 3 个 table:

我需要 return 前 10 位客户。

我使用了这个查询:

SELECT TOP 10 
    CustomerID, COUNT(CustomerID)
FROM
    Sales
GROUP BY
    (CustomerID)
ORDER BY 
    COUNT(CustomerID) DESC

查询目前return只有customerId和计数,但我还需要return这些客户的firstNamelastName来自Person table.

我知道我需要通过 Sales.customerIdCustomer.customerId 之间的关联来达到 firstNamelastName,并从 Customer.personId 获得 Person.personId.

我的问题是我是否需要使用内部联接或联合,以及如何使用它们中的任何一个来获取这些客户的 firstNamelastName

并集主要用于不相交的集合。为了实现你的目标,你可以使用 inner-join。

如果您想使用联接,那么这里是与您的要求类似的查询。

SELECT TOP 10 S.CustomerID, P.FirstName,P.LastName, count(*) 
FROM Sales S 
   INNER JOIN Customer C on S.CustomerId=C.CustomerId
   INNER JOIN Person P on C.PersonId = P.PersonId
GROUP BY (S.CustomerID, P.FirstName,P.LastName) 
ORDER BY count(*) DESC

您需要像这样使用 inner join :

SELECT TOP 10   S.CustomerID
              , P.FirstName
              , P.LastName
              , COUNT (1) AS CountOfCustomer -- this is equal count(*)
  FROM  Sales S
        INNER JOIN Customer C ON S.CustomerId = C.CustomerId
        INNER JOIN Person P ON C.PersonId = P.PersonId
 GROUP BY S.CustomerID, P.FirstName, P.LastName
 ORDER BY 4 DESC; -- this is equal order by count(*)