替代Sybase中的SQL窗口函数

时间:2014-07-31 08:33:21

标签: sybase sybase-ase window-functions

我正在使用Sybase Adaptive Server Enterprise(版本12.5.0.3)。试图使用Row_number() OVER (Partition by columnname order by columnname)。当我执行查询时,它抛出一个异常,说OVER附近的语法不正确。我搜索了sybase数据库的正确row_number()语法,但语法没有错。我想正在使用的Sybase版本不支持row_number() OVER。我甚至试过dense_rank() OVER,但我得到了同样的错误。

我需要知道它是否真的是语法问题还是因为Sybase的低版本不支持关键字?

如果问题与版本有关,那么对于sybase数据库,是否存在row_number OVER和dense_rank()OVER的替代方法。

我的查询:

select  cr.firstname, cr.lastname, cr.dob,cr.phone,
          row_number() over (patition by cr.dob order by createddate) "rank"       
          from ff.CrossReferenceTable cr

错误讯息:

Server Message:  Number  156, Severity  15
               Server 'MyServer', Line 1:
               Incorrect syntax near the keyword 'over'.

2 个答案:

答案 0 :(得分:3)

是的,遗憾的是,Sybase ASE不支持row_number()功能以及rank()dense_rank()。 但是,在一些简单的情况下,如果不使用partition子句,它可以像

那样进行转换
select rank=identity(music), * into #new_temp_tab1 from CrossReferenceTable order by createddate
select firstname, lastname, dob, phone, rank from #new_temp_tab1

在你的情况下,它会变得有点复杂,我建议使用带有临时表的游标来模拟row_number()的行为分区。 请看下面的示例:

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

答案 1 :(得分:0)

请尝试以下通用查询与ROW_NUMBER()相同

SELECT 
  A.MyPartitionColumn, 
  A.MyRunningNumberColumn, 
  ( SELECT count(*) 
    FROM MyTable 
    WHERE    MyPartitionColumn      = A.MyPartitionColumn
         AND MyRunningNumberColumn <= A.MyRunningNumberColumn
  ) AS "Row_Number"
FROM      MyTable  A
ORDER BY  MyPartitionColumn, MyRunningNumberColumn