Ranking in SQL

I have group of riders that log miles ridden on the website. Miles are saved and summed in a mileagelog table. Currently they are ordered by total miles by the year. New requirement is to have an indicator that show if a rider's progress in relation to others.
I can calculate their current position using this code.
declare @year int
set @year = 2014
declare @ridepost table
riderid int
, [currentspot] int
, [priorspot] int
, movement int
, [year] int
;with numberedrows
as
(SELECT m.riderid, sum(m.distancemiles) as [distance], 0 as [prior],@year as [year],
'N' as [movement], ROW_NUMBER() OVER (ORDER BY sum(m.distancemiles)desc) AS position
FROM mileagelog m
WHERE m.ridetypeid <> 7
and DATEPART(YYYY,ridedate) = @year
group by m.riderid
insert into BDUC.riderspot
select riderid
, position
, [prior]
, movement
, [year]
from numberedrows
This orders all of the riders for the year. The problem I have is how to show changes.  The table riderspot has the rider and year. ON INSERT the position column is set to their current position the prior set to 0 and the movement flag set to 'N' (new).
If a rider inserts a new mileage the prior column is set ti the previous position and the position should be set to the new position. If the new position passes one or more riders that were ahead of him his movement is set to 'U' (up) and any riders he passed
are set to 'D' (down). The ruder may also delete a ride in which case he should be flagged as 'D' (down) and those that passed him = 'U'. If he adds miles but does not pass anyone his movement = 'S' (static). And of course if he ties it is set to 'T' as is
the rider he ties with. Simple eh? Any Ideas?
This is my attempt at assigning positions...
DECLARE @riderid int
select @riderid = 670
DECLARE @year int
select @year = 2014
declare @current int
declare @prior int
declare @movement char(1)
declare @rider2 int
declare @riderspot table
rider int
, [current] int
, [prior] int
, movement char(1)
, [year] int
-- if there is a rw for the rider/year...
IF exists (select * from BDUC.riderspot where riderid = @riderid and curyear = @year )
--Update records
SELECT @prior = (SELECT currentspot from BDUC.riderspot WHERE riderid = @riderid and curyear = @year)
select @prior
DECLARE @mileagerank TABLE
( distance float
, riderid int
, rowcounter int
;with currentrows
as
(SELECT riderid, sum(distancemiles) as [distance], ROW_NUMBER() OVER (ORDER BY sum(distancemiles)desc) AS RowNumber
FROM mileagelog
WHERE DATEPART(YYYY,ridedate) = @year
AND ridetypeid <> 7
group by riderid)
insert into @mileagerank select nr.[distance], nr.riderid, nr.RowNumber from currentrows nr
JOIn riders r
on r.riderid = nr.riderid
SELECT @current = (select rowcounter from @mileagerank where riderid = @riderid )
SELECT @current
select @movement = case when @current < @prior then 'U'
WHEN @current > @prior then 'D'
WHEN @current = @prior then 'S'
ELSE 'N'
END
SELECT @movement
UPDATE BDUC.riderspot
SET currentspot = @current
, priorspot = @prior
, movement = @movement
WHERE riderid = @riderid
and curyear = @year

Dave,
Read about different ranking functions in sql server in an article I wrote here..
http://sqlsaga.com/sql-server/what-is-the-difference-between-rank-dense_rank-row_number-and-ntile-in-sql-server/
If you have posted some sample DDL and DML, it would have been much easier to help you than work with the actual query...
Please mark as answer, if this has helped you solve the issue.
Good Luck :) .. visit www.sqlsaga.com for more t-sql code snippets and BI related how to articles.

Similar Messages

  • How to use rank inside SQL results of a dashboard prompt

    I am trying to find last updated date of fact table, last updated date of fact table - 7, last updated date of fact table -21 etc. to be populated in a dashboard prompt and for which I thought i could use Oracle rank() over last_updated_date using a sql synatx like this.
    select Periods."Current Week Date" from(SELECT Periods."Current Week Date", RANK(Periods."Current Week Date" BY Periods."Current Week Date") ra FROM "Summit 08" where "Current Week Facts By Product"."Current Week Gross Sales" > 0 order by Periods."Current Week Date" desc) where ra = 1 or ra=7 or ra =21
    Error that comes up says
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 27001] End of input has been reached. Illegal syntax. (HY000)
    SQL Issued: select Periods."Current Week Date" from(SELECT Periods."Current Week Date", RANK(Periods."Current Week Date" BY Periods."Current Week Date") ra FROM "Summit 08" where "Current Week Facts By Product"."Current Week Gross Sales" > 0 order by Periods."Current Week Date" desc)
    This does not work.. any one with suggestions
    As always, appreciate your help and thanks in advance
    Message was edited by:
    user566193

    Hi...
    No dual will not work.. here..
    try this.. if you want to show only the national, region and city strings..
    *select case when 1=0 then any varchar hold column from your subject area else 'National' end from SubjectAreaName*
    union all
    *select case when 1=0 then any varchar hold column from your subject area else 'Region' end from SubjectAreaName*
    union all
    *select case when 1=0 then any varchar hold column from your subject area else 'City' end from SubjectAreaName*
    here any varchar hold column from your subject area is any column from existing subject area.. which holds character values.. like.. Markets. Region
    I think you know where it need to be written.. in Show SQL part of your prompt..
    All the best..
    Edited by: Kishore Guggilla on Feb 12, 2009 8:30 PM

  • RANK FUNCTION IN ORACLE 8I

    제품 : PL/SQL
    작성날짜 : 2001-09-11
    RANK FUNCTION IN ORACLE 8I
    ==========================
    EXPLANATION
    oracle 8i(8.1.6) 부터 가능한 rank function 입니다.
    8.1.5 에서는 ora-923 error 가 납니다.
    plsql 내에서는 oracle 9i 부터 가능합니다.
    8.1.6에서는 ora-900 error가 납니다.
    EXAMPLE
    <RANK() OVER ( query_partition_clause ORDER_BY clause) >
    - 중복 rank 값만큼 다음 순위는 생략
    SQL>SELECT deptno, ename, sal, comm,
    RANK() OVER (PARTITION BY deptno ORDER BY sal DESC, comm) as rk
    FROM emp;
    DEPTNO ENAME SAL RK
    10 KING 5000 1
    10 CLARK 2450 2
    10 MILLER 1300 3
    20 3500 1
    20 SCOTT 3000 2
    20 FORD 3000 2
    20 JONES 2975 4
    20 ADAMS 1100 5
    20 SMITH 800 6
    30 BLAKE 2850 1
    30 ALLEN 1600 2
    30 TURNER 1500 3
    30 WARD 1250 4
    30 MARTIN 1250 5
    40 JAMES 777 1
    9 1
    <DENSE_RANK( ) OVER ( query_partition_clause ORDER_BY clause ) >
    - 중복 rank 의 수와 무관하게 numbering
    SQL>SELECT dname, ename, sal, DENSE_RANK()
    OVER (PARTITION BY dname ORDER BY sal) as drank
    FROM emp, dept
    WHERE emp.deptno = dept.deptno
    AND dname IN ('SALES', 'RESEARCH');
    DNAME ENAME SAL DRANK
    RESEARCH SMITH 800 1
    RESEARCH ADAMS 1100 2
    RESEARCH JONES 2975 3
    RESEARCH SCOTT 3000 4
    RESEARCH FORD 3000 4
    RESEARCH 3500 5
    SALES WARD 1250 1
    SALES MARTIN 1250 1
    SALES TURNER 1500 2
    SALES ALLEN 1600 3
    SALES BLAKE 2850 4
    plsql 내에서 사용 가능 :oracle 9i 부터
    SQL> create table
    rank_emp(deptno number(2), ename varchar2(20), sal number(5), rk number(2));
    테이블이 생성되었습니다.
    SQL> create or replace procedure window_plsql AS
    query_str VArchar2(1000);
    begin
    query_str := 'insert into rank_emp
    SELECT deptno, ename, sal,
    RANK() OVER (PARTITION BY deptno ORDER BY sal DESC, comm) as rk
    FROM emp' ;
    Execute Immediate query_str;
    end;
    2 /
    프로시저가 생성되었습니다.
    SQL> exec window_plsql
    PL/SQL 처리가 정상적으로 완료되었습니다.
    SQL> select * from rank_emp;
    DEPTNO ENAME SAL RK
    10 KING 5000 1
    10 CLARK 2450 2
    10 MILLER 1300 3
    20 SCOTT 3000 1
    20 FORD 3000 1
    20 JONES 2975 3
    20 ADAMS 1100 4
    20 SMITH 800 5
    30 BLAKE 2850 1
    30 ALLEN 1600 2
    30 TURNER 1500 3
    DEPTNO ENAME SAL RK
    30 WARD 1250 4
    30 MARTIN 1250 5
    30 JAMES 950 6
    14 개의 행이 선택되었습니다.

    That's correct
    The differences between Standard and Enterprise Edition are listed here:
    http://www.oracle.com/technology/products/oracle8i/pdf/8i_fam.pdf

  • Ranking query Required ( as not in oracle built in rank functions )

    Hai I have facing some kind of problem with Ranking using sql, i want different ranking as not in oracle built in functions ,
    Please help me
    for Example, i am showing the sample data what i required Exactly
    if any student obtains the same marks rank should be bottom rank of the students who got same rank which should cummulate top students rank
    Ranking Procedure - 1
    =========================
    sno Student Marks Rank
    =========================
    1 x00013 50 2
    2 x00021 50 2
    3 x00012 49 5
    4 x00001 49 5
    5 x00002 49 5
    6 x00033 48 10
    7 x00034 48 10
    8 x00015 48 10
    9 x00088 48 10
    10 x00051 48 10
    11 x00044 47 11
    12 x00041 48 12
    =======================
    Ranking Procedure - 2
    =========================
    sno Student Marks Rank
    =========================
    1 x00013 50 1
    2 x00021 50 1
    3 x00012 49 3
    4 x00001 49 3
    5 x00002 49 3
    6 x00033 48 6
    7 x00034 48 6
    8 x00015 48 6
    9 x00088 48 6
    10 x00051 48 6
    11 x00044 47 7
    12 x00041 48 8
    =======================
    regards
    Mahesh

    Why are you excluding Oracle built in functions? The results of "Ranking Procedure 2" would appear to just be the result of
    SELECT sno, student, marks, RANK() OVER (ORDER BY marks DESC) rnk
      FROM your_tablei.e.
      1  with x as (
      2  select 1 sno, 13 student, 50 marks from dual
      3  union all
      4  select 2, 21, 50 from dual
      5  union all
      6  select 3, 12, 49 from dual
      7  )
      8  select sno, student, marks, rank() over (order by marks desc) rnk
      9*   from x
    SCOTT @ jcave102 Local> /
           SNO    STUDENT      MARKS        RNK
             1         13         50          1
             2         21         50          1
             3         12         49          3I would probably write a custom analytic function to get the results of your first ranking procedure. Though I imagine you could get the same results in pure SQL, a well-named custom aggregate function would seem to be easier to understand (though the pure SQL solution may well be somewhat more efficient).
    Justin

  • @Rank function using EVALUATE

    Hi short question,
    I'm trying to get the @rank function to work in combination with OBIEE 10.1.3.4 (using EVALUATE). Anyone here already tried using this with Essbase version 9.2? In some of the documentation it states this can not be done using anything below Essbase 9.3 but the @Rank function is available within v9.2 Is there any limit on using this from the OBIEE side?
    I used this reference:
    (how to:) http://oraclebizint.wordpress.com/2008/04/28/oracle-bi-ee-101332-handling-sort-order-in-hyperion-essbase-931-evaluate-and-mdx/
    (Essbase 9.2 doc --> @Rank available) http://download.oracle.com/docs/cd/E12032_01/doc/epm.921/html_techref/techref.htm
    Evaluate function I'm trying to launch is:
    EVALUATE(’RANK(%1.dimension.currentmember,%2.members)’ AS INTEGER,Period."PeriodGen4",Period."PeriodGen4")
    Am I doing something wrong here, or am I trying to do things which can't be done?
    Thanks in advance,
    Mathijs

    I tried the syntax
    EVALUATE ('RANK(%1,%2)' as integer,"Account"."Gen4,Account Default","Account"."Gen4,Account Default")
    but still i am getting the error as:-
    Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 43113] Message returned from OBIS. [nQSError: 96002] Essbase Error: Syntax error in input MDX query on line 6 at token 'RANK' (HY000)
    SQL Issued: SELECT s_0, s_1, s_2, s_3, s_4, s_5, s_6, s_7 FROM ( SELECT 0 s_0, "FINRPTC#1"."Account"."Gen3,Account Default" s_1, "FINRPTC#1"."Account"."Gen4,Account Default" s_2, "FINRPTC#1"."FinancialYear"."Gen2,FinancialYear" s_3, "FINRPTC#1"."Period"."Gen3,Period" s_4, EVALUATE ('RANK(%1,%2)' as integer,"FINRPTC#1"."Account"."Gen4,Account Default","Account"."Gen4,Account Default") s_5, "FINRPTC#1"."FINRPTC"."Actual" s_6, REPORT_AGGREGATE("FINRPTC#1"."FINRPTC"."Actual" BY "FINRPTC#1"."Account"."Gen3,Account Default","FINRPTC#1"."Account"."Gen4,Account Default","FINRPTC#1"."FinancialYear"."Gen2,FinancialYear","FINRPTC#1"."Period"."Gen3,Period") s_7 FROM "FINRPTC#1" WHERE (("FinancialYear"."Gen2,FinancialYear" = 'FY12') AND ("Period"."Gen3,Period" = 'Nov') AND ("Account"."Gen3,Account Default" = 'Net Cost of Services')) ) djm

  • Passing parameters to table valued functions and using parameters as column name on select

    I am creating a function where I want to pass it parameters and then use those parameters in a select statement. When I do that it selects the variable name as a literal not a column. How do I switch that context.
    Query:
    ALTER FUNCTION [dbo].[ufn_Banner_Orion_Employee_Comparison_parser_v2]
    @BANNER_COLUMN AS VARCHAR(MAX),
    @ORION_COLUMN AS VARCHAR(MAX)
    RETURNS @Banner_Orion_Employee_Comparison TABLE 
    LAST_NAME nvarchar(max),
    EMPNO int,
    BannerColumnName nvarchar(max),
    BANNER nvarchar(max),
    ORION nvarchar(max)
    AS
    BEGIN
    INSERT INTO @Banner_Orion_Employee_Comparison
    (LAST_NAME, BANNER, ORION)
    SELECT
    a.LAST_NAME, @BANNER_COLUMN, @ORION_COLUMN
    FROM OPENQUERY(ORCLPROD_APDORACLE, 'select LAST_NAME, BANNER_RANK, BADGE, EMP_STATUS from XTRACT_VIEW') AS a
    inner join IWM_Stage.dbo.ViewPersonnel AS b
    on a.BADGE = b.badge
    WHERE a.EMP_STATUS = 'A'
    and a.BANNER_RANK <> b.[rank]
    RETURN;
    END;
    GO
    Output
    I execute this:
    select * from ufn_Banner_Orion_Employee_Comparison_parser_v2 ('a.BANNER_RANK' , 'b.[rank]')
    and get:
    Cerecerez NULL
    NULL a.BANNER_RANK
    b.[rank]
          

    George,
    You could go for using a CASE statement as earlier mentioned by Erland. This would look like below: (Downside is that you need to be mentioning all possible values in the CASE)
    ALTER FUNCTION [dbo].[ufn_Banner_Orion_Employee_Comparison_parser_v2]
    @BANNER_COLUMN AS VARCHAR(MAX),
    @ORION_COLUMN AS VARCHAR(MAX)
    RETURNS @Banner_Orion_Employee_Comparison TABLE
    LAST_NAME nvarchar(max),
    EMPNO int,
    BannerColumnName nvarchar(max),
    BANNER nvarchar(max),
    ORION nvarchar(max)
    AS
    BEGIN
    INSERT INTO @Banner_Orion_Employee_Comparison(LAST_NAME, BANNER, ORION)
    SELECT
    a.LAST_NAME
    , CASE @BANNER_COLUMN WHEN 'a.BANNER_RANK' THEN a.BANNER_RANK WHEN 'a.BADGE' THEN a.BADGE END --put values as required
    , CASE @ORION_COLUMN WHEN 'b.[rank]' THEN b.[rank] END --put values as required
    FROM OPENQUERY(ORCLPROD_APDORACLE, 'select LAST_NAME, BANNER_RANK, BADGE, EMP_STATUS from XTRACT_VIEW') AS a
    inner join IWM_Stage.dbo.ViewPersonnel AS b
    on a.BADGE = b.badge
    WHERE a.EMP_STATUS = 'A'
    and a.BANNER_RANK <> b.[rank]
    RETURN;
    END;
    GO
    Another method that I would suggest is to get all values from the function, then build a dynamic query to obtain results from it .. Something like:
    ALTER FUNCTION [dbo].[ufn_Banner_Orion_Employee_Comparison_parser_v2]()
    RETURNS @Banner_Orion_Employee_Comparison TABLE
    LAST_NAME nvarchar(max),
    EMPNO int,
    BannerColumnName nvarchar(max),
    BANNER nvarchar(max),
    ORION nvarchar(max)
    AS
    BEGIN
    INSERT INTO @Banner_Orion_Employee_Comparison(LAST_NAME, BANNER, ORION)
    SELECT
    * --Returns all the columns
    FROM OPENQUERY(ORCLPROD_APDORACLE, 'select LAST_NAME, BANNER_RANK, BADGE, EMP_STATUS from XTRACT_VIEW') AS a
    inner join IWM_Stage.dbo.ViewPersonnel AS b
    on a.BADGE = b.badge
    WHERE a.EMP_STATUS = 'A'
    and a.BANNER_RANK <> b.[rank]
    RETURN;
    END;
    GO
    --Execution
    DECLARE @BANNER_COLUMN AS VARCHAR(MAX), @ORION_COLUMN AS VARCHAR(MAX),@SQL NVARCHAR(MAX)
    SET @BANNER_COLUMN='BANNER_RANK'
    SET @ORION_COLUMN='[rank]'
    SET @SQL='
    select LAST_NAME,'+@BANNER_COLUMN+','+@ORION_COLUMN+' from ufn_Banner_Orion_Employee_Comparison_parser_v2 ()'
    PRINT @SQL
    EXEC @SQL
    You just need to make sure that the column names returned by the function are UNIQUE (Using proper alias names) so that you don't have a problem referring to them from the outside..
    Thanks,
    Jay
    <If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>

  • Assigning sequential numbers for every lines within a group of records

    The scenario is:
    This set of records with group number, lets say 100(group number) contains 7 lines/records. How to assign line numbers (sequential) for each line within these groups on the fly during the mapping process before inserting these set of rows in the target. I know it is easy to achieve in a procedure, but not sure how to do this in the mapping.
    please advice.
    Thanks,
    Prabha

    Use Rank function
    SQL> select empno,ename,deptno,(rank() over (partition by deptno order by empno)) seqno from emp;
    EMPNO ENAME DEPTNO SEQNO
    7782 CLARK 10 1
    7839 KING 10 2
    7934 MILLER 10 3
    7369 SMITH1 20 1
    7566 JONES 20 2
    7788 SCOTT 20 3
    7876 ADAMS 20 4
    7902 FORD 20 5
    7499 ALLEN 30 1
    7521 WARD 30 2
    7654 MARTIN 30 3
    7698 BLAKE 30 4
    7844 TURNER 30 5
    7900 JAMES 30 6
    1111 Test 40 1
    1222 test 1
    1333 2
    17 rows selected

  • How can I cancel span class="text" ?

    I've been working on a web page, and I've spent much of my
    time deleting
    <span class="text">, along with the closing
    </span> tag. Dreamweaver is
    inserting them automatically. Is there some way to turn this
    feature off?
    Thanks.

    mdonahue wrote:
    > Or you can go to the Insert Menu >
    > HTML > Special Characters > Other... to find the
    character you're looking for.
    > Mike
    >
    That's how I used to insert apostrophes. I just visually
    selected the
    character that looks like an apostrophe - &#8217; - and
    used it in all
    my articles. But a member of this newsgroup recently informed
    me that
    &#8217; isn't an apostrophe - it's a single right quote
    (apparently
    designed to complement &#8216;.
    I then asked what code DOES constitute an apostrophe, and my
    understanding is that there is no code for an apostrophe.
    Apparently, an
    apostrophe is represented by a single slanted mark that looks
    like
    something like an apostrophe.
    I just tried to copy one from one of my web pages to this
    e-mail without
    success until I copied it in code view: ’
    I don't know what it will look like once I send this message,
    but here
    it is again to the left of a "stick-figure" apostrophe I
    created by
    simply pushing a key on my keyboard:
    Funny thing is, I used to work hard at tracking those things
    down and
    deleting them. I thought they were Windows annoyances or
    something
    similar. As I recall, I couldn't do a proper search and
    replace for them
    in Dreamweaver on my PC; I had to copy the entire article
    into Notepad.
    Weird.
    Anyway, I asked some related questions on another forum and
    came away
    with the impression that you cannot insert proper apostrophes
    with
    Dreamweaver, nor did I figure out how to do it in any other
    software
    program. Pretty amazing, but I can only assume other writers
    do what I
    did - grab a good apostrophe on the Internet and copy and
    paste it in
    all their work.
    I was going to ask another question: How does one create
    stylized, or
    literary apostrophes that gracefully curve as you increase
    the size of
    your text? I could have sworn &#8217; did take on a
    curved appearance as
    it increases in size.
    However, I just pasted it alongside one of those simple
    slanted
    apostrophes with no numerical code, then increased the text
    size in my
    browser and see no difference. Neither one looks especially
    cool.
    Honestly, all this special character stuff ranks with SQL
    injection as
    one of web design's biggest mysteries. ;)

  • Sql query slowness due to rank and columns with null values:

        
    Sql query slowness due to rank and columns with null values:
    I have the following table in database with around 10 millions records:
    Declaration:
    create table PropertyOwners (
    [Key] int not null primary key,
    PropertyKey int not null,    
    BoughtDate DateTime,    
    OwnerKey int null,    
    GroupKey int null   
    go
    [Key] is primary key and combination of PropertyKey, BoughtDate, OwnerKey and GroupKey is unique.
    With the following index:
    CREATE NONCLUSTERED INDEX [IX_PropertyOwners] ON [dbo].[PropertyOwners]    
    [PropertyKey] ASC,   
    [BoughtDate] DESC,   
    [OwnerKey] DESC,   
    [GroupKey] DESC   
    go
    Description of the case:
    For single BoughtDate one property can belong to multiple owners or single group, for single record there can either be OwnerKey or GroupKey but not both so one of them will be null for each record. I am trying to retrieve the data from the table using
    following query for the OwnerKey. If there are same property rows for owners and group at the same time than the rows having OwnerKey with be preferred, that is why I am using "OwnerKey desc" in Rank function.
    declare @ownerKey int = 40000   
    select PropertyKey, BoughtDate, OwnerKey, GroupKey   
    from (    
    select PropertyKey, BoughtDate, OwnerKey, GroupKey,       
    RANK() over (partition by PropertyKey order by BoughtDate desc, OwnerKey desc, GroupKey desc) as [Rank]   
    from PropertyOwners   
    ) as result   
    where result.[Rank]=1 and result.[OwnerKey]=@ownerKey
    It is taking 2-3 seconds to get the records which is too slow, similar time it is taking as I try to get the records using the GroupKey. But when I tried to get the records for the PropertyKey with the same query, it is executing in 10 milliseconds.
    May be the slowness is due to as OwnerKey/GroupKey in the table  can be null and sql server in unable to index it. I have also tried to use the Indexed view to pre ranked them but I can't use it in my query as Rank function is not supported in indexed
    view.
    Please note this table is updated once a day and using Sql Server 2008 R2. Any help will be greatly appreciated.

    create table #result (PropertyKey int not null, BoughtDate datetime, OwnerKey int null, GroupKey int null, [Rank] int not null)Create index idx ON #result(OwnerKey ,rnk)
    insert into #result(PropertyKey, BoughtDate, OwnerKey, GroupKey, [Rank])
    select PropertyKey, BoughtDate, OwnerKey, GroupKey,
    RANK() over (partition by PropertyKey order by BoughtDate desc, OwnerKey desc, GroupKey desc) as [Rank]
    from PropertyOwners
    go
    declare @ownerKey int = 1
    select PropertyKey, BoughtDate, OwnerKey, GroupKey
    from #result as result
    where result.[Rank]=1
    and result.[OwnerKey]=@ownerKey
    go
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Prob in using rank in pl/sql ,need logic same of rank function in any way

    I have a query as of the following <br>
    <br>
    SELECT sr_no,cod_acct_no,dat_arrears_due,amt_arrear_due<br>
    FROM ( select cod_acct_no,dat_arrears_due,sum(amt_arrears_due) <br>amt_arrear_due,rank() over (partition by cod_acct_no order by <br>dat_arrears_due asc) sr_no<br>
              from arrears_table <br>
              where amt_arrears_due > 0<br>
    and dat_arrears_due <= to_date('31/10/2006','dd/mm/yyyy')<br>
    and COD_ARREAR_TYPE = 'C'<br>
         group by cod_acct_no,dat_arrears_due<br>
         ) Z <br>
    WHERE z.sr_no <=5 <br>
    <br>
    I have to use this in a cursor in pl/sql but because i have rank analytic function <br>
    I am facing a compilation error ORA-06550: error <br>
    <br>
    Can you give me a logic which gives same output as of above <br>
    <br>
    Regards<br>
    vamsi krishna<br>
    <br>
    <br>

    [1]: (Error): ORA-06550: line 5, column 28: PLS-00103: Encountered the <br>symbol "(" when expecting one of the following: , from <br>
    <br>
    My oracle version is <br>
    Oracle8i Enterprise Edition Release 8.1.6.0.0 - Production<br>
    PL/SQL Release 8.1.6.0.0 - Production<br>
    CORE 8.1.6.0.0 Production<br>
    TNS for 32-bit Windows: Version 8.1.6.0.0 - Production<br>
    NLSRTL Version 3.4.1.0.0 - Production<br>
    <br>I think it is comming for rank function it self <br>
    <br> will this version support analytic (rank) function's in pl/sql cursors<br>
    Regards<br>
    vamsi krishna<br>

  • Pl/SQL Rank() function problem

    Hello everyone....i hv been using Oracle10g for a while now....
    I hv a question which I'm not able to solve now...
    I have this query which shows top 3 employee records based on their joiningdate...the older the joiningdate the higher would be his rank.
    so i run this query....
    select * from(select * rank() over(order by joiningdate desc)daterank from employee) where daterank<=3;
    Following error occurs:
    ERROR at line 1:
    ORA-00923: FROM keyword not found where expected
    How do i solve this problem???
    Edited by: 781207 on Jul 9, 2010 9:42 PM

    Check this query
    1 select empno ,deptno,Hiredate,
    2 dense_rank() OVER (PARTITION BY deptno ORDER BY hiredate) slno
    3* from emp
    SQL> /
    EMPNO DEPTNO HIREDATE SLNO
    7782 10 09-JUN-81 1
    7839 10 17-NOV-81 2
    7934 10 23-JAN-82 3
    7369 20 17-DEC-80 1
    7566 20 02-APR-81 2
    7902 20 03-DEC-81 3
    7788 20 19-APR-87 4
    7876 20 23-MAY-87 5
    7499 30 20-FEB-81 1
    7521 30 22-FEB-81 2
    7698 30 01-MAY-81 3
    EMPNO DEPTNO HIREDATE SLNO
    7844 30 08-SEP-81 4
    7654 30 28-SEP-81 5
    7900 30 03-DEC-81 6
    14 rows selected.
    SQL> ed
    Wrote file afiedt.buf
    1 select empno ,deptno,Hiredate,
    2 dense_rank() OVER (ORDER BY hiredate) slno
    3* from emp
    SQL> /
    EMPNO DEPTNO HIREDATE SLNO
    7369 20 17-DEC-80 1
    7499 30 20-FEB-81 2
    7521 30 22-FEB-81 3
    7566 20 02-APR-81 4
    7698 30 01-MAY-81 5
    7782 10 09-JUN-81 6
    7844 30 08-SEP-81 7
    7654 30 28-SEP-81 8
    7839 10 17-NOV-81 9
    7900 30 03-DEC-81 10
    7902 20 03-DEC-81 10
    EMPNO DEPTNO HIREDATE SLNO
    7934 10 23-JAN-82 11
    7788 20 19-APR-87 12
    7876 20 23-MAY-87 13
    14 rows selected.
    SQL>

  • How to get rank within the row in SQL

    I have an a key orderid and 4 other columns with orderdate&time in (16/12/2011 16:15:24 format) within a table.
    the orderid has an average of 1million rows every week hence could not do this in excel for a 15 day period .
    ORderid.........: mail........................................ : telephone ............................:online ........................................ store.......................... Agency
    A3456...........15/12/2011 16:15:24 ............... 16/12/2011 14:12:01.............16/12/2011 16:14:00..........17/12/2011 11:22:55 ............12/12/2011 22:20:30
    B678
    C555
    i want to create a new table which ranks each row according to the max orderdate and time say in another table
    i want to capture the rank
    KEY.......Mail............Tel............online.........store..........Agency
    A3456.....4 ...............3...............2...............1............... 5
    Is there any way either within the same table or in other table i wiould be able to get the rank based on the rows in SQL.
    thnks
    Edited by: UOOLK on 29-Dec-2011 06:46

    Something like this I think:
    create new_order_table as
      select order_id
            ,rank() over (order by mail desc) mail
            ,rank() over (order by telephone desc) telephone
            ,rank() over (order by online desc) online
            ,rank() over (order by store desc) store
            ,rank() over (order by agency desc) agency
        from old_order_table;Assuming you want the most recent date to be ranked number 1. If you want number 1 to be the oldest then remove all the 'desc's from the order by clauses.

  • Using Ranking on MS SQL Server 2005

    Hello,
    We are on BOXI3.1 base version and have a universe on top of MS SQL Server 2005.
    My question is regarding use of rank functions. BO guides state that
    You can perform a database ranking only if your database supports
    it. If this is not the case, the Add a database ranking button is disabled on
    the Query Panel toolbar. Databases that support ranking are Oracle, DB2,
    Terradata and Redbrick.
    So SQL Server is not in the list. However the add database ranking button is enabled on
    my report panel. If i add a ranking the query runs for a long time and times-out.
    Is there any universe parameter i need to enable to use ranking? Has any-one mangaged to
    use ranking functionality with SQL Server 2005.
    Thanks in advance.

    Hi Bashir Awan,
    When we create this Object (using your example) at Universe level is the ranking hardcoded ?
    My questions is, say i have Product object (with values A, B, C, D, E), and sales aggregated (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
    Say the table is as follows
    Product;        sales
        A;               10
        A;                70*
        B;                 50
        B;                 20*
        C;                 30
        C;                 60*
        D;                 40
        D;                 90
        E;                 80
        E;                100
    Note: * represents Oversees sales outside US
    Case 1: Now when we rank whole data to select top 3 we should get (E, D, C in Desc order)
    Case 2: Now if I apply prompt on Country of sales as US will I get (E, B, D) or is it still (E, D, C as earlier).
    Case 3: Similarly if I apply prompt on Product (no prompt on Country) in the filter pane and select (A, D, E) will my results show (E, D, A) or (E, D) as the value of A may be restricted due to ranking formula based on sales at Universe level.
    I am sorry I may be asking a very basic question. Thanks
    Sudhir.

  • Dear SQL-Experts:  RANK() OVER (...) - Function

    Hello,
    I'm looking for a solution for the following SQL-SELECT-Problem.
    Imagine a table or a view with
    many items with a composite key (5 columns)
    some item-specific data columns and...
    ...at least an integer-column which counts double or more entrys of items with the same key (call it U_EntryCnt)
    What I need is a SELECT-Statement which SELECTs all Items BUT only one of the double entrys (if there are doubles).
    It should SELECT only that one of the double entrys which has the maximum number of the double-entrys in the U_EntryCnt-column.
    My idea is to create a VIEW like (three key-columns in this example):
    SELECT
         RANK() OVER (PARTITION BY U_KeyCol1, U_KeyCol2, U_KeyCol3 ORDER BY U_EntryCnt DESC) AS Rank,
         U_KeyCol1, U_KeyCol2, U_KeyCol3,
         U_DatCol1, U_DatCol2,..........U_DatColN,
            U_EntryCnt
    FROM
         [@TST_EXAMPLE]
    And afterwards SELECTing FROM that VIEW WHERE Rank=1
    A test on a little example table seems to work. But could somebody tell me is this is the right way?
    Thanks,
    Roland
    PS.:
    GROUP BY does not work in my opinion. When I want to SELECT any column, this column must be added to the GROUP BY statement. Once a selected data col differs within the same key doubles I get two results of the same key and this is not wanted.

    Hi Robin,
    thanks for your answer. (I hope I've understand everything right - this problem also seems to lead me to the boundary of my english ;-/ )
    Within the double-key-rows the MAX-Aggregat gives me not the correct result: It does not return the data from the row with the MAX(U_EntryCnt) but rather the maximum of the data within the double-key-rows.
    The best would be an complete example.
    Here is the example-table with (unsorted) keys, data and the entry-counter (only one example DataCol for clearness):
    KeyCol1 |KeyCol2 |KeyCol3 |DataCol1     |EntryCnt
    ================================================
    A     |A     |1       |AA1 XXX     |1
    B     |B     |1       |BB1 Wanted     |2
    A     |A     |1       |AA1 Wanted     |2
    B     |B     |1       |BB1 XXX     |1
    C     |C     |1       |CC1 Wanted     |1
    The wanted rows are marked with "Wanted" in the Data colum for example. Technically they're wanted because these rows are containing the maximum EntryCnt-Number within their key-double rows.
    Robin:
    When you talk about sub-select I think you mean sth. like this:
    SELECT
         T0.U_KeyCol1, T0.U_KeyCol2, T0.U_KeyCol3, MAX(T0.U_EntryCnt),
         (SELECT T1.U_DatCol1
         FROM [@TST_EXAMPLE] T1
         WHERE
         T0.U_KeyCol1=T1.U_KeyCol1 AND
         T0.U_KeyCol2=T1.U_KeyCol2 AND
         T0.U_KeyCol3=T1.U_KeyCol3 AND
         T1.U_EntryCnt=MAX(T0.U_EntryCnt)) AS DatCol1,
         (SELECT T1.U_DatColN
         FROM [@TST_EXAMPLE] T1
         WHERE
         T0.U_KeyCol1=T1.U_KeyCol1 AND
         T0.U_KeyCol2=T1.U_KeyCol2 AND
         T0.U_KeyCol3=T1.U_KeyCol3 AND
         T1.U_EntryCnt=MAX(T0.U_EntryCnt)) AS DatColN
    FROM
         [@TST_EXAMPLE] T0
    GROUP BY
         T0.U_KeyCol1, T0.U_KeyCol2, T0.U_KeyCol3
    Yes: this also works.
    As far as I know every column needs it's own subSelect. Very extensive when we talk about 20 to 40 columns.
    If the RANK function really gives the same result under all circumstances (in this example it does) it's much easier:
    First create a VIEW which contains a Rank-column:
    CREATE VIEW [dbo].[@TST_EXAMPLE_VIEW] AS
    SELECT
         RANK() OVER (PARTITION BY U_KeyCol1, U_KeyCol2, U_KeyCol3 ORDER BY U_EntryCnt DESC) AS Rank,
         Code, Name,
         U_KeyCol1, U_KeyCol2, U_KeyCol3,
         U_DatCol1, U_DatCol2, U_DatCol3, U_DatCol4,
         U_EntryCnt
    FROM
         [@TST_EXAMPLE]
    And now the condition WHERE Rank=1 seems to give the wanted rows (in the example it does :-):
    SELECT * FROM [@TST_EXAMPLE_VIEW] WHERE Rank=1
    Because this is a much more clearly arranged query, it would be nice if somebody could confirm that this is also a right way.
    Another question is which of the two Query-examples may have the best SQL-Server performance (which ist faster)

  • Sql tuning using rank function

    Hi,
    Can someone help me in writing the below qry using rank() function?
    DELETE FROM stc_calllog_ext a
    WHERE a.stc_save_status = 'CT'
    AND ROWID IN (SELECT a.ROWID
    FROM stc_calllog_ext a, calllog_ext b
    WHERE a.prod_line_code= b.prod_line_code
    AND a.brand_code = b.brand_code
    AND a.model_number = b.model_number
    AND a.stc_save_status != b.stc_save_status
    AND trunc(a.stc_start_time) = trunc(b.stc_start_time)
    AND a.stc_start_time BETWEEN TRUNC(SYSDATE-8) AND TRUNC(SYSDATE)
    AND a.call_taker_userid = b.call_taker_userid
    AND a.cons_telephone_no =b.cons_telephone_no
    )

    With the information you have provided, I've come up with the following.
    SELECT A.ACCOUNT_NO, A.PAYMENT_TYPE, A.INSTALLMENT_TYPE, A.DATE_CHANGE
    FROM
        (SELECT account_no, payment_type, installment_type, date_change,
                LEAD( (payment_type), 1)
                     over (partition by account_no order by account_no, DATE_CHANGE)  LEAD_PAY,
                LEAD( (installment_type), 1)
                     over (partition by account_no order by account_no, DATE_CHANGE)  LEAD_INST
          from T_ACCNTS ) A
    WHERE A.PAYMENT_TYPE <> NVL(A.LEAD_PAY,99)
       OR A.INSTALLMENT_TYPE <> NVL(A.LEAD_INST,99)
    ORDER BY 1, 4;

Maybe you are looking for

  • Problem in using the enhancement SAPLV01Z for batch no assignment

    Hi, i am using the enhancement SAPLV01Z for using the user defined batch number. In which i am allowing the system to generate the internal batch number if it is newly created batch for that particular material,site and MRP combination.For this i am

  • Query manager View issue in PIA

    Hi, When i navigate through reporting tools,Query,querymanager i am not able to see options like records,query,expressions,prompts.Fields,Criteria,Having,Viewsql,Run in Query manager window. When i go to the Application designer and tried to run Quer

  • Apache2 httpd.conf on Snow Leopard 10.6.3

    Hello there, I've got a problem with the httpd.conf file. I made some changes and then nothing worked. After that i found /etc/apache2/original/httpd.conf and thought that this must be the original and copied it to /etc/apache2/ but then i noticed th

  • Mustek SE A3 1200 scanner no longer seems to work with Mac pro

    Hi, I have a Mustek SE A3 usb 1200 pro scanner and it just recently stoped working [I think it is since I updated to Mavericks.] I tried looking for a new driver but there is only one for mac for my scanner. The problem is when I open Image Acquire a

  • Datasource has a minus sign

    Hi, I created a datasource on R3 and saw it from RSA6. I checked the Datasource Overview and saw it is there, but the sign for the activation column is a minus and not a plus. I tried to assign datasource to an infosource, and the datasource did not