2017-07-28 51 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 | 
+----+------+---------+--------------+ 

而且,這聽起來像功課 - 如果是這樣,我建議把在的問題,以防止假設。

相關問題