尋找低於
替代了查詢,而不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]
尋找低於
替代了查詢,而不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]
我們可以嘗試用標識列創建tablevariable並插入選定的數據得到ROW_NUMBER作爲輸出
declare @test table (i int identity(1,1), test varchar(10))
這與這個問題有什麼關係? –
不能使用表變量,尋找一個查詢和類似的連接或分組。 – Tony
雖然我覺得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];
爲什麼你正在尋找一個替代? – p2k
由於某種原因,應用程序提供商不喜歡它 – Tony
大聲笑...也許他/她想降級到MS Access? –