SQL在select中使用select获得每年的结果

时间:2018-12-10 12:06:09

标签: sql sql-server tsql

我正在研究罗斯文数据库以进行SQL研究,并试图每年显示购买金额最高的客户。

在我看来,我需要在一个选择中进行选择才能获得我正在寻找的结果。我正在设法为客户获得最大量的订单,但我无法订购或仅按年分开订购。

这是我到目前为止要做的:

select top 1 
    (count([Order Details].OrderID)) 'NumOfOrders',
    Customers.CompanyName, year(OrderDate) 'OrderYear'
from 
    [Order Details], Orders, Customers
where 
    [Order Details].OrderID = Orders.OrderID 
    and Orders.CustomerID = Customers.CustomerID 
    and (year(OrderDate) = 1996 or year(OrderDate) = 1997 or year(OrderDate) = 1998)
group by 
    Customers.CompanyName, year(OrderDate)
order by 
    NumOfOrders desc

2 个答案:

答案 0 :(得分:1)

如果从脚本中删除TOP 1,您将看到所需的内容。 但是就像戈登所说的那样,您需要提高查询能力。 我为您找到了一些链接,您可以检查它们:

适合您的示例脚本:

SELECT 
     C.CompanyName
    ,YEAR(O.OrderDate) AS 'OrderYear'
    ,(COUNT(O.OrderID)) AS 'NumOfOrders'
FROM [Order Details] AS OD
INNER JOIN Orders AS O ON OD.OrderID = O.OrderID
INNER JOIN Customers AS C ON O.CustomerID = C.CustomerID
WHERE   YEAR(O.OrderDate) IN(1996,1997,1998)
GROUP BY C.CompanyName
        ,YEAR(O.OrderDate)
ORDER BY 
        C.CompanyName
        ,YEAR(O.OrderDate)
        ,NumOfOrders DESC

答案 1 :(得分:1)

如果我对您要实现的目标有正确的理解(每年最有价值的客户中排名前1位),那么您可以尝试以下方法:

SELECT  TOP 1 WITH TIES
        t.NumOfOrders, 
        t.CompanyName, 
        t.OrderYear,
        ROW_NUMBER() OVER (PARTITION BY t.OrderYear 
                            ORDER BY t.NumOfOrders DESC ) AS RN
FROM (  SELECT      COUNT(OD.OrderID) AS [NumOfOrders] ,
                    C.CompanyName,
                    YEAR(OrderDate) AS [OrderYear]
        FROM    [Order Details] AS OD 
                    JOIN [Orders] AS O ON OD.OrderID = O.OrderID
                    JOIN Customers AS C ON O.CustomerID = C.CustomerID
        WHERE  YEAR(OrderDate) IN (1996, 1997, 1998)
        GROUP BY C.CompanyName, YEAR(OrderDate)
     ) AS T
ORDER BY RN