我有一个示例查询
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 ,
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
关于sql - 想要在现有的选择语句中再添加两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13049031/