Postgreの関数は詳しくないので適当に読み替えてみてください
SQL
1create table tbl(KEY1 varchar(20),KEY2 varchar(10),KEY3 varchar(10));
2insert into tbl values
3('A1191028000001','00002','0'),
4('B1191028000001','00001','1'),
5('B1191028000002','00001','1'),
6('B1191028000003','00002','1'),
7('C1191028000001','00002','1'),
8('C1191028000002','00002','1');
9
10
11select * from tbl as t1
12where not exists
13(select 1 from tbl where
14 substr(KEY1,1,2)=substr(t1.KEY1,1,2) and
15 KEY1>t1.KEY1
16);
調整
- KEY1を比較
- 同じならKEY2を比較
- 同じならKEY3を比較
- すべて同じなら1個だけ
SQL
1create table tbl(KEY1 varchar(20),KEY2 varchar(10),KEY3 varchar(10));
2insert into tbl values
3('A1191028000001','00002','0'),
4('B1191028000001','00001','1'),
5('B1191028000002','00001','1'),
6('B1191028000003','00002','0'),
7('B1191028000003','00002','1'),
8('C1191028000001','00002','1'),
9('C1191028000002','00001','1'),
10('C1191028000002','00002','0'),
11('D1191028000001','00001','0'),
12('D1191028000001','00001','0');
13
14
15select distinct * from tbl as t1
16where not exists
17(select 1 from tbl where
18 (substr(KEY1,1,2)=substr(t1.KEY1,1,2) and
19 (KEY1>t1.KEY1 or
20 KEY1=t1.KEY1 and KEY2>t1.KEY2 or
21 KEY1=t1.KEY1 and KEY2=t1.KEY2 and KEY3>t1.KEY3
22 )
23 )
24);