问题
I am working on Sybase Adaptive Server Enterprise (version 12.5.0.3). Trying to use Row_number() OVER (Partition by columnname order by columnname)
. When I execute the query it is throwing an exception saying that the syntax near OVER is incorrect. I have searched for proper row_number() syntax for sybase database, but there is nothing wrong in the syntax. I guess that the Sybase version that am using does not support row_number() OVER
. I even tried dense_rank() OVER
, but am getting the same error.
I need to know whether it is really a syntax issue or its because of Sybase's low version which is not supporting the key words?
If the issue is with the version, then is there any alternative for row_number OVER and dense_rank() OVER for sybase database.
My Query:
select cr.firstname, cr.lastname, cr.dob,cr.phone,
row_number() over (patition by cr.dob order by createddate) "rank"
from ff.CrossReferenceTable cr
Error Message:
Server Message: Number 156, Severity 15
Server 'MyServer', Line 1:
Incorrect syntax near the keyword 'over'.
回答1:
Right, unfortunately Sybase ASE doesn't support row_number()
function as well as rank()
and dense_rank()
.
However, in some simple cases, where partition clause is not used it could be converted in the way like
select rank=identity(music), * into #new_temp_tab1 from CrossReferenceTable order by createddate
select firstname, lastname, dob, phone, rank from #new_temp_tab1
In your case it's going to be a little bit more complicated, I can recommend using cursor with temporary table to emulate row_number()
over partition by behavior.
Please have a look at the example below:
create table CrossReferenceTable(firstname varchar(50),lastname varchar(50), dob int,phone char(10), createddate date)
create proc sp_CrossReferenceTable
as
begin
declare @i int
declare @cur_firstname varchar(50)
declare @cur_lastname varchar(50)
declare @cur_dob int
declare @cur_phone varchar(10)
declare @cur_rank int
declare cur cursor for select cr.firstname, cr.lastname, cr.dob,cr.phone, count(*) AS "rank" from CrossReferenceTable cr
group by cr.dob ORDER BY cr.dob, createddate
CREATE TABLE #CrossReferenceTable_TEMP(firstname varchar(50),lastname varchar(50), dob int,phone char(10),rank INT)
open cur
fetch cur into @cur_firstname , @cur_lastname , @cur_dob , @cur_phone , @cur_rank
set @i = @cur_rank
while @@SQLSTATUS = 0
begin
if @i = 0
set @i = @cur_rank
insert into #CrossReferenceTable_TEMP select @cur_firstname , @cur_lastname , @cur_dob , @cur_phone,
case when @cur_rank > 1 then @cur_rank - (@i - 1) ELSE @cur_rank end as "rank"
set @i = @i - 1
fetch cur into @cur_firstname , @cur_lastname , @cur_dob , @cur_phone , @cur_rank
end
select firstname, lastname, dob, phone, rank from #CrossReferenceTable_TEMP
end
exec sp_CrossReferenceTable
来源:https://stackoverflow.com/questions/25054267/alternative-to-sql-window-functions-in-sybase