Reputation: 543
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:
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
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