SQL Query返回前2个值

时间:2014-11-12 17:12:33

标签: sql sql-server tsql sql-server-2012 top-n

我正在尝试返回客户数据库中排名最前2位的商品。以下是我对最有序的项目所拥有的内容,但是我无法弄清楚如何为第二个最有序的项目创建另一个列。

创建第二列的最佳方法是什么?

SELECT FirstName, EmailAddress, Id, PreferredLocationId, 
(
     SELECT TOP 1 [Description] FROM [Order] o 
     INNER JOIN [OrderItem] oi ON oi.OrderId = o.OrderId
     WHERE o.CustomerId = Customer.Id
     GROUP BY [Description]
     ORDER BY COUNT(*) DESC
) AS MostOrderedItem
FROM Customer
GROUP BY FirstName, EmailAddress, Id, PreferredLocationId

1 个答案:

答案 0 :(得分:3)

如果你正在使用SQL Server 2012,很多方法可以处理这个问题。我将使用CTE获取前两行并使用ROW_NUMBER()

WITH cte AS (
  SELECT CustomerId, [Description]
    , ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY COUNT(*) DESC) [RowID]
  FROM [Order] o 
  INNER JOIN [OrderItem] oi ON oi.OrderId = o.OrderId
  GROUP BY CustomerId, [Description]
)
SELECT FirstName, EmailAddress, Id, PreferredLocationId, cte1.Description, cte2.Description
FROM Customer
LEFT JOIN cte cte1 ON cte1.CustomerID = Customer.CustomerId AND cte1.RowID = 1
LEFT JOIN cte cte2 ON cte2.CustomerID = Customer.CustomerId AND cte2.RowID = 2

Common Table Expression创建所有客户,描述及其行号的列表。请注意,如果您有联系,那么您将不会首先了解哪种说明。你可以添加到窗口函数描述,这样如果有一个平局,那么字母表中的第一个就是领带破坏者。