您可以用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