SQL 服务器 - 我将如何对上个月的产品进行排名?

SQL Server - How would I rank products from the last month?

我已经开始充实一些内容,但是我在添加某种 window 函数以获得在我的代码中调用数据、产品的预期结果时遇到了问题按上月销售额排名。如果可以提供任何帮助,我将不胜感激!

这是被问到的问题:

The CEO would like to know the sales based on last month's sales. Please provide her with a query to rank the products by the number of orders in the last month. There should be NO SKIPPED NUMBERS.

这是我目前得到的:

SELECT 
    P.NAME AS 'Product Name',
    Isnull(Count(DISTINCT O.OrderID), 0) AS 'Orders Count',
    Sum(Isnull(o.ordertotal, 0)) AS 'Orders Total',
    Sum (Isnull(oi.orderitemquantity, 0)) AS 'Item Total'
 FROM 
    Product P
 INNER JOIN 
    OrderItem OI ON OI.ProductID = P.ProductID
 INNER JOIN 
    Orders O ON O.OrderID = OI.OrderID
GROUP BY 
    P.Name

这也需要在存储过程中,因此任何帮助也将非常有用。

您可以使用 CTERANK() 函数

create procedure yourProcedure (@TheDate datetime = null)
as

if @TheDate is null 
begin
   set @TheDate = getdate()
end

;with cte as(
SELECT 
    P.NAME AS 'Product Name',
    Isnull(Count(DISTINCT O.OrderID), 0) AS 'Orders Count',
    Sum(Isnull(o.ordertotal, 0)) AS 'Orders Total',
    Sum (Isnull(oi.orderitemquantity, 0)) AS 'Item Total'
 FROM 
    Product P
 INNER JOIN 
    OrderItem OI ON OI.ProductID = P.ProductID
 INNER JOIN 
    Orders O ON O.OrderID = OI.OrderID
WHERE
    --here is the limiting to the previous month based off the month passed in
    SomeDateField >= DATEADD(MONTH, DATEDIFF(MONTH, 0, @TheDate)-1, 0)
    and
    SomeDateField < DATEADD(month, DATEDIFF(month, 0, @TheDate), 0)
GROUP BY 
    P.Name)

select
    *
    ,DENSE_RANK() over (order by [Orders Count]) as RK
from cte

DENSE_RANK() 不会跳过数字,而 RANK() 可能取决于您的数据集。

例子

declare @table table (ID int identity (1,1), item int)
insert into @table
values
(1),
(2),
(3),
(3),
(3),
(3),
(4),
(5),
(6)

select 
    * 
    ,rank() over (order by item) TheRank
    ,dense_rank() over (order by item) TheDenseRank
from @table

+----+------+---------+--------------+
| ID | item | TheRank | TheDenseRank |
+----+------+---------+--------------+
|  1 |    1 |       1 |            1 |
|  2 |    2 |       2 |            2 |
|  3 |    3 |       3 |            3 |
|  4 |    3 |       3 |            3 |
|  5 |    3 |       3 |            3 |
|  6 |    3 |       3 |            3 |
|  7 |    4 |       7 |            4 | --notice difference starting here
|  8 |    5 |       8 |            5 |
|  9 |    6 |       9 |            6 |
+----+------+---------+--------------+

此外,这听起来像是家庭作业——如果是,我建议将其放在问题中以防止假设。