Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select first match based on column rule

Problem Statement: need any first match based on hier rules column defined
Example: like no match for hier 1, but hier 2 is matched, then select sec_id for hier 2

Sample:

with cte_tab as (select column1 as hier, column2 as rule, column3 as sec_id from values
       (1, 'NO','COM'), (1, 'NO','COM'), (2, 'NO','COM'), (3, 'YES','COM')
    order by column1)
select * from cte_tab;

Expected Output:
From the example below, the expected output would be the row with hier = 3 as it’s the first match from the group for which rule=’YES’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Note: there could be multiple entries for the hier and returning all of them is a valid scenario if the rule = ‘YES’ is valid for that group.

enter image description here

>Solution :

Using QAULIFY and DENSE_RANK:

with cte_tab as (
   select column1 as hier, column2 as rule, column3 as sec_id 
   from values
       (1, 'NO','COM'), (1, 'NO','COM'), (2, 'NO','COM'), (3, 'YES','COM')
   order by column1)
select * 
from cte_tab
QUALIFY DENSE_RANK() OVER(ORDER BY RULE='YES' DESC, HIER) = 1;

This version returns only YES for HIER 3

Output:

enter image description here


If the goal is to get entire HIER 3 regardless of rule then:

with cte_tab as (
    select column1 as hier, column2 as rule, column3 as sec_id 
    from values
       (1, 'NO','COM'), (1, 'NO','COM'), (2, 'NO','COM'),
       (3, 'YES','COM'), (3, 'NO', 'A')
    order by column1)
select * 
from cte_tab
QUALIFY HIER=(ARRAY_AGG(HIER) WITHIN GROUP(ORDER BY RULE='YES' DESC) OVER())[0]::TEXT

Output:

enter image description here

Related: Equivalent for Keep in Snowflake

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading