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 a record a variable number of times based on two different fields on the same table

I’m not an expert of ANSI SQL and I need to write the following query.

This is the table from which I start:

ID Max_Recurrency Priority
abc 2 1
abc 2 450
abc 2 12
def 1 827
def 1 44
def 1 112
ghi 2 544
ghi 2 4
ghi 2 95
ghi 2 25

The output I need is something like this:

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

ID Max_Recurrency Priority
abc 2 450
abc 2 12
def 1 827
ghi 2 544
ghi 2 95

In other words, I need to select the ID of the record as many times as is indicated in the Max_Recurrency field and select the records with the highest Priority, i.e. excluding those with the lowest Priority if the Max_Recurrency field has a value less than the number of times the ID is repeated in the table.

Can anyone help me?

>Solution :

We can use ROW_NUMBER here:

WITH cte AS (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Priority DESC) rn
    FROM yourTable t
)

SELECT ID, Max_Recurrency, Priority
FROM cte
WHERE rn <= Max_Recurrency;
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