2017-07-28 66 views
1

我已经开始充实一些东西了,但是我在添加某种窗口函数时遇到问题,无法获得预期的结果,即在我的代码中调用的数据,产品在上个月按销售排名。如果有任何帮助,我将不胜感激!SQL Server - 我如何对上个月的产品进行排名?

这是问什么:

的CEO想知道,根据上个月的销售量销售。 请为她提供一个查询,以便在上个月根据 订单数量对产品进行排名。应该没有跳过的数字。

这里是我到目前为止有:

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 

这确实需要在存储过程中一样,所以有任何帮助将是巨大的。

+0

SQL Server有一个功能:https://docs.microsoft.com/en-us/sql/t-sql/functions/dense-rank-transact-sql – Caramiriel

+0

好吧pal - 就像@ Caramiriel说的那样根据您提供的标准,RANK数据可用于您的功能。将它作为存储过程创建时有什么问题或疑问? – Leonidas199x

+0

请提供样本数据和您已经尝试过的内容。 – Eli

回答

1

您可以用CTE做到这一点,一个RANK()功能

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 | 
+----+------+---------+--------------+ 

而且,这听起来像功课 - 如果是这样,我建议把在的问题,以防止假设。

相关问题