我有一个示例查询
select
x as 1, y as 2 , z as 3
from
table abc, xyz
where
a = x and x = 123
SELECT
现在我想在这个语句中再添加两列,如下所示:
- 第 4 列将显示行序号。
- 第 5 列:此列将取决于行 - 它将显示
start
在第一行、Last
最后一行以及Middle
其间的任何行中。
请建议最好的优化方法来做到这一点。
谢谢
我有一个示例查询
select
x as 1, y as 2 , z as 3
from
table abc, xyz
where
a = x and x = 123
SELECT
现在我想在这个语句中再添加两列,如下所示:
start
在第一行、Last
最后一行以及Middle
其间的任何行中。请建议最好的优化方法来做到这一点。
谢谢
除非您指定,否则数据没有顺序。
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
请注意在上述查询中使用 ANSI-92 连接而不是 where 子句。
您可以使用公用表表达式进一步优化它
;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
或者没有这样的 CTE:
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