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

时间:2012-10-24 12:16:24

标签: 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

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

  1. 第4列,将显示行序列号。
  2. 第5列:此列将取决于行 - 它将在第一行显示start,在最后一行显示Last,在其间的任何行显示Middle
  3. 请建议最好的优化方法。

    谢谢

1 个答案:

答案 0 :(得分: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

请注意在上述查询中使用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