CREATE table sampletb(id int, stack varchar(10));
INSERT into sampletb values(1,'a');
INSERT into sampletb values(1,'b');
INSERT into sampletb values(2,'c');
INSERT into sampletb values(2,'d');
SELECT * FROM sampletb;
id stack
----------- ----------
1 a
1 b
2 c
2 d
SELECT id,
stack,
row_number() over (partition by id order by stack) as row_number
from sampletb;
このクエリにより、次のような結果が得られます。
id stack row_number
----------- ---------- --------------------
1 a 1
1 b 2
2 c 1
2 d 2
上記のクエリをサブクエリとして作成し、列を取得すると、
row_number=1
必要な出力が得られます。
select id,stack from
(
SELECT id,
stack,
row_number() over (partition by id order by stack) as row_number
FROM sampletb) x
where x.row_number=1;
id stack
----------- ----------
1 a
2 c