ROW_NUMBER()
を使用します :
SELECT
name,
ROW_NUMBER() OVER (ORDER BY name) AS id
FROM people;
編集:
ORDER BY 1
の違い vs ORDER BY column_name
SELECT
name,
ROW_NUMBER() OVER (ORDER BY name) AS id
FROM people;
/* Execution Plan */
QUERY PLAN WindowAgg (cost=83.37..104.37 rows=1200 width=38)
-> Sort (cost=83.37..86.37 rows=1200 width=38)
**Sort Key: name**
-> Seq Scan on people (cost=0.00..22.00 rows=1200 width=38)
SELECT
name,
ROW_NUMBER() OVER (ORDER BY 1) AS id
FROM people;
/* Execution Plan */
QUERY PLAN WindowAgg (cost=0.00..37.00 rows=1200 width=38)
-> Seq Scan on people (cost=0.00..22.00 rows=1200 width=38)
2番目のケースでは、ソート操作はありません。
2番目のクエリを次のように記述することもできます:
SELECT
name,
ROW_NUMBER() OVER () AS id
FROM people;
人々がORDER BY 1
を書く理由 ウィンドウ関数で?
一部の方言では必須であり、ORDER BY 1
プレースホルダーのように機能します。
オラクル:
SELECT
name,
ROW_NUMBER() OVER (ORDER BY 1) AS id
FROM people;
TSQL:
SELECT
name,
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS id
FROM people;