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

Difference of top two values while GROUP BY

Suppose I have the following SQL Table:

id | score
------------
1  |  4433
1  |  678
1  |  1230
1  |  414
5  |  8899
5  |  123
6  |  2345
6  |  567
6  |  2323

Now I wanted to do a GROUP BY id operation wherein the score column would be modified as follows: take the absolute difference between the top two highest scores for each id.

For example, the response for the above query should be:

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  |  score
------------
1   |  3203
5   |  8776
6   |  22

A quick guide on how to perform this query in PostgreSQL would be appreciated.

>Solution :

Using ROW_NUMBER along with pivoting logic we can try:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY score DESC) rn
    FROM yourTable
)

SELECT id,
       ABS(MAX(score) FILTER (WHERE rn = 1) -
               MAX(score) FILTER (WHERE rn = 2)) AS score
FROM cte
GROUP BY id;

Demo

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