Custom Search
www.rocket99.com : Technical Guides Sybase Oracle UNIX Javascript


Technical Guides
Sybase
Oracle
UNIX
Javascript




Of Interest

Business Intelligence and Analytics



Oracle Training





Sybase » T-SQL » »

Sybase IQ - Lead / Lag Functions

     



Sybase IQ does not have native lead and lag functions .. here is how to add these as custom functions.





create function fn_lead (
@table_nm varchar(30),
@column_nm varchar(30),
@filter_fld_nm varchar(30),
@filter_fld_val integer,
@pivot_fld_nm varchar(30),
@pivot_fld_val integer, @span integer )
returns real
as

declare @sqlcmd varchar(1000),
@pivot real,
@i integer

select @i = 0

while (@i < @span)
begin

select @i = @i + 1

select @sqlcmd = 'select @pivot=' +
'min(' + @pivot_fld_nm + ') ' + ' from ' + @table_nm +
' where ' + @pivot_fld_nm + ' > ' + convert(varchar(15), @pivot_fld_val )

execute (@sqlcmd)

select @pivot_fld_val = @pivot

end



declare @val real

select @sqlcmd = 'select @val = ' + @column_nm + ' from ' + @table_nm + ' where ' +
@filter_fld_nm + ' = ' + convert( varchar(12),@filter_fld_val ) + ' and ' +
@pivot_fld_nm + ' = ' + convert( varchar(12),@pivot )

execute (@sqlcmd)


return @val
go



-- sample call

declare @val real

select @val = fn_lead ( 'sales_history','gross_sales','salesman_id',333, 'period_id',200404,2)

select @val as result111
go







create function fn_lag (
@table_nm varchar(30),
@column_nm varchar(30),
@filter_fld_nm varchar(30),
@filter_fld_val integer,
@pivot_fld_nm varchar(30),
@pivot_fld_val integer, @span integer )
returns real
as

declare @sqlcmd varchar(1000),
@pivot real,
@i integer

select @i = 0

while (@i < @span)
begin

select @i = @i + 1

select @sqlcmd = 'select @pivot=' +
'max(' + @pivot_fld_nm + ') ' + ' from ' + @table_nm +
' where ' + @pivot_fld_nm + ' < ' + convert(varchar(15), @pivot_fld_val )

execute (@sqlcmd)

select @pivot_fld_val = @pivot

end



declare @val real

select @sqlcmd = 'select @val = ' + @column_nm + ' from ' + @table_nm + ' where ' +
@filter_fld_nm + ' = ' + convert( varchar(12),@filter_fld_val ) + ' and ' +
@pivot_fld_nm + ' = ' + convert( varchar(12),@pivot )

execute (@sqlcmd)


return @val
go



-- sample call


declare @val real

select @val = fn_lag ( 'flight_log','total_complaints','flight_key',555, 'period_id',200404,2)

select @val as result111
go











Sybase : Related Topics

Sybase : T-SQL : Sybase IQ - Showing Multiple Result Sets

Sybase Web Site
Sybase iAnywhere Mobile Web Site
Oracle Enterprise Web Site



Get the latest Rocket99 news and tech tips via






Site Index About this Guide to Sybase, Oracle, and UNIX Contact Us Advertise on this site




Copyright © 2016 Stoltenbar Inc All Rights Reserved.