您可以用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 |
+----+------+---------+--------------+
而且,這聽起來像功課 - 如果是這樣,我建議把在的問題,以防止假設。
SQL Server有一個功能:https://docs.microsoft.com/en-us/sql/t-sql/functions/dense-rank-transact-sql – Caramiriel
好吧pal - 就像@ Caramiriel說的那樣根據您提供的標準,RANK數據可用於您的功能。將它作爲存儲過程創建時有什麼問題或疑問? – Leonidas199x
請提供樣本數據和您已經嘗試過的內容。 – Eli