想在现有的select语句中添加两列

ash*_*ish 3 sql sql-server sql-server-2005

我有一个示例查询

select 
    x as 1, y as 2 , z as 3 
from 
    table abc, xyz
where 
    a = x and x = 123
Run Code Online (Sandbox Code Playgroud)

现在我想在此SELECT语句中添加两个列,如下所示:

  1. 第4列将显示行序列号.
  2. 第5列:此列将取决于行 - 它将显示start在第一行,Last最后一行和Middle中间的任何行中.

请建议最好的优化方法来做到这一点.

谢谢

pod*_*ska 6

除非您指定数据,否则数据没有订单.

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
Run Code Online (Sandbox Code Playgroud)

请注意在上述查询中使用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
Run Code Online (Sandbox Code Playgroud)

或者没有像这样的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
Run Code Online (Sandbox Code Playgroud)