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

How to select one instance each, based on distinct column values using UNION

This is the input data:
enter image description here

I just want 1 instance for each work_contract.

I tried to use LIMIT 1 and used UNION ALL as well as UNION DISTINCT but it appears we can’t use LIMIT in UNION.

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

SELECT *,
FROM table1 
where work_contract = "SECONDMENT" 
LIMIT 1

UNION DISTINCT

SELECT *,
FROM table1 
where work_contract = "INTER" 
LIMIT 1

UNION DISTINCT

SELECT *,
FROM table1 
where work_contract = "CASUAL" 
LIMIT 1

This doesn’t work. Is there a way to choose only 1 instance at work_contract level?

>Solution :

you can use below query. I am assuming here you don’t want to include at employee id level and its just work_contract level.

SELECT *,
FROM table 1 
where work_contract = "SECONDMENT" 
qualify ( row_number() over  (partition by work_contract order by employee_id,employee_type_description) = 1)

UNION DISTINCT

SELECT *,
FROM table 1   
where work_contract = "INTER" 
qualify ( row_number() over  (partition by work_contract order by employee_id,employee_type_description) = 1)

UNION DISTINCT

SELECT *,
FROM table 1   
where work_contract = "CASUAL" 
qualify ( row_number() over  (partition by work_contract order by employee_id,employee_type_description) = 1)
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