3

サンプルクエリがあります

select 
    x as 1, y as 2 , z as 3 
from 
    table abc, xyz
where 
    a = x and x = 123

SELECT次に、次のように、このステートメントにさらに 2 つの列を追加します。

  1. 行シーケンス番号を表示する列4。
  2. 列 5: この列は行によって異なります。start最初の行、Last最後の行、およびMiddleその間の行に表示されます。

これを行うための最善の最適化方法を提案してください。

ありがとう

4

1 に答える 1

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

上記のクエリでは、WHERE 句の代わりに ANSI-92 結合を使用していることに注意してください。

共通テーブル式を使用して、これをさらに最適化できる場合があります

;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
于 2012-10-24T12:18:33.097 に答える