我首先尝试排序记录,然后区分它们(不同的PersonID,但通过获取整个行内容而不重复PersonID)在oracle上使用单个查询。
在示例中:按RecordType排序(p first)然后获取不同的PersonID列表
案例1的期望结果:
(1,'John', 'Doe', 2,'P' );
(2,'Scot', 'Mic', 1,'P' );
案例2的预期结果:
(1,'John', 'Doe', 1,'S' );
(2,'Scot', 'Mic', 1,'P' )
SQL:
drop table test_records;
CREATE TABLE test_records
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
RecordId int,
RecordType varchar(255)
);
1 case:
insert into test_records values(1,'John', 'Doe', 1,'S' );
insert into test_records values(1,'John', 'Doe', 2,'P' );
insert into test_records values(1,'John', 'Doe', 3,'S' );
insert into test_records values(1,'John', 'Doe', 4,'S' );
insert into test_records values(1,'John', 'Doe', 1,'S' );
insert into test_records values(2,'Scot', 'Mic', 1,'P' );
2 case:
insert into test_records values(1,'John', 'Doe', 1,'S' );
insert into test_records values(1,'John', 'Doe', 2,'S' );
insert into test_records values(1,'John', 'Doe', 3,'S' );
insert into test_records values(1,'John', 'Doe', 4,'S' );
insert into test_records values(1,'John', 'Doe', 1,'S' );
insert into test_records values(2,'Scot', 'Mic', 1,'P' );
答案 0 :(得分:2)
我认为分析row_number()
电话是您正在寻找的
SELECT PersonID, LastName, FirstName, RecordId, RecordType
FROM (SELECT PersonID, LastName, FirstName, RecordId, RecordType,
ROW_NUMBER() OVER (PARTITION BY PersonID ORDER BY RecordType ASC) AS rn
FROM test_records) t
WHERE rn = 1