简体   繁体   English

SQL select 最大分组

[英]SQL select Group by with max

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'
        );
       

output : for each unique values of(p_id, d_id, t_id) we should get two records with max version available output :对于(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.

You could use the max and count window functions as the following:您可以使用 max 和 count window 函数,如下所示:

Select p_id, d_id, t_id, version, source, name, county  
From
(
  Select *,
    Max(version) Over (Partition By p_id, d_id, t_id) max_ver,
    Count(*) Over (Partition By p_id, d_id, t_id, version) cnt
  From table_name
) T
Where version = max_ver And cnt = 2
Order By p_id, d_id, t_id

Another option, you could use aggregation as the following:另一种选择,您可以使用聚合如下:

Select p_id, d_id, t_id, version, source, name, county
From table_name T
Where (p_id, d_id, t_id, version) In
(
  Select p_id, d_id, t_id, Max(version)
  From table_name
  Group By p_id, d_id, t_id
)
And 
(
  Select Count(*) H From table_name D 
  Where 
  D.p_id=T.p_id And D.d_id=T.d_id And D.t_id=T.t_id And D.version=T.version
) = 2 
Order By p_id, d_id, t_id

See a demo .看一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM