Create Table table_name(p_id VARCHAR(50), d_id VARCHAR(50), t_id VARCHAR(50), version INT, source VARCHAR(50), name VARCHAR(50), county VARCHAR(50));
Insert Into table_name Values('p1','d1','t1',2,'online','penny','usa'),
('p1','d1','t1',2,'manual','penny','india'),
('p1','d1','t1',1,'online','penny','india'),
('p1','d1','t1',1,'manual','penny','usa'),
('p2','d2','t2',4,'online','david','india'),
('p2','d2','t2',4,'online','david','usa'),
('p2','d2','t2',1,'online','david','usa'),
('p2','d2','t2',1,'manual','david','india'),
('P3','d3','d3',3,'online','raj','india');
select * from table
where (p_id, d_id, t_id, version)
in (
select p_id, d_id, t_id, version from table
where (p_id, d_id, t_id, version)
in ( select p_id, d_id, t_id, max(version) from table group by p_id, d_id, t_id ) //1. fetch distinct of (p_id, d_id, t_id) and with max(version)
group by p_id, d_id, t_id, version
having count(*)>1 //2. get only records which has both source = online and source = manual. note-- we should ignore p3 because it doesn't have both online and manual'
);
输出:对于(p_id,d_id,t_id)的每个唯一值,我们应该获得两个具有最大可用版本的记录
results: p2-d2-t2 with version 4
p1-d1-t1 and p3-d3-t3 should be ignored because it has only one value.
1条答案
按热度按时间qyswt5oh1#
可以按如下方式使用max和count窗口函数:
另一种选择是,您可以按如下方式使用聚合:
参见demo。