簡體   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 :對於(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.

您可以使用 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

另一種選擇,您可以使用聚合如下:

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

看一個演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM