2016-09-23 109 views
-1

寻找低于
替代了查询,而不row_number() over(partition by替代为“ROW_NUMBER()以上(分区由”

select *,row_number() over(partition by [Tag Name],[PRD] order by [Start Time]) num 
from [PRD Project].[Data].[efan1] 
+0

为什么你正在寻找一个替代? – p2k

+0

由于某种原因,应用程序提供商不喜欢它 – Tony

+0

大声笑...也许他/她想降级到MS Access? –

回答

0

我们可以尝试用标识列创建tablevariable并插入选定的数据得到ROW_NUMBER作为输出

declare @test table (i int identity(1,1), test varchar(10)) 
+0

这与这个问题有什么关系? –

+0

不能使用表变量,寻找一个查询和类似的连接或分组。 – Tony

0

虽然我觉得ROW_NUMBER可能是做到这一点的最佳方式,这里有一个替代方案。

的设置:

CREATE TABLE [#test] ([Col1] CHAR(1) -- This is what we're partitioning by 
        , [Col2] INT); -- This is what we're ordering by 

INSERT INTO [#test] 
SELECT CHAR(ABS(CHECKSUM(NEWID()))%16+65) -- Random single letters A:P 
     , ABS(CHECKSUM(NEWID())) % 1000  -- Random numbers 1:1000 
FROM [sys].[objects]; 

的查询:

-- Original ROW_NUMBER query 
SELECT * 
     , ROW_NUMBER() OVER(PARTITION BY [Col1] ORDER BY [Col2]) AS [RN] 
FROM [#test] 
ORDER BY [Col1] 
     , [rn]; 


-- Alternative w/ CROSS APPLY 
SELECT * 
FROM [#test] [t1] 
     -- For each row in #test, 
     -- Get the number of rows in #test where our partitioning column (Col1) is the same and the ordering column (Col2) is lower 
     -- Add 1 to get the initial value to start at 1 instead of 0 (i.e. for the first value per partition, there are 0 rows with a lower ordering value) 
     CROSS APPLY (SELECT COUNT(*) + 1 AS [rn] 
        FROM [#test] [t2] 
        WHERE [t1].[Col1] = [t2].[Col1] 
         AND [t1].[Col2] > [t2].[Col2]) [t2] 
ORDER BY [Col1] 
     , [rn];