ashish
ashish

Reputation: 543

Wanted to add two more column , in existing select statement

I have a sample query

select 
    x as 1, y as 2 , z as 3 
from 
    table abc, xyz
where 
    a = x and x = 123

Now I want to add two more columns in this SELECT statement like this:

  1. column 4 which will show the row sequence no.
  2. column 5: this column will depend on the row - it will show start in first row, Last in the last row and Middle in any rows in between.

Please suggest the best possible optimize way to do this.

Thanks

Upvotes: 3

Views: 903

Answers (1)

podiluska
podiluska

Reputation: 51494

Data doesn't have an order unless you specify it.

select 
    x as 1, 
    y as 2 , 
    z as 3 ,
    row_number() over (order by whatever),
    case when row_number() over (order by whatever) = 1 then 'first' 
    else
        case when row_number() over (order by whatever desc) = 1 then 'last' 
        else 'middle' 
        end
    end
from table abc 
    inner join xyz on a = x 
where x= 123

Note the use of ANSI-92 joins instead of a where clause in the above query.

You may be able to optimise this further using a Common Table Expression

;with cte as 
(
    select 
        x , 
        y , 
        z  ,
        row_number() over (order by whatever) rn
    from table abc 
        inner join xyz on a = x 
    where x= 123
)
    select x,y,z,rn,
        case rn when 1 then 'first'
        when (select MAX(rn) from cte) then 'last'
        else 'middle'
    end
    from cte

Or without a CTE like this:

select 
    x as 1, 
    y as 2 , 
    z as 3 ,
    row_number() over (order by whatever),
    case row_number() over (order by whatever)
        when 1 then 'first' 
        when count(*) over () then 'last' 
        else 'middle' 
    end
from table abc 
    inner join xyz on a = x 
where x= 123

Upvotes: 6

Related Questions