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

Scalar subquery producing more than 1 record with partition – SQL

I have data with two rows as follows:

group_id    item_no
weoifne     1
weoifne     2

I want to retrieve the max item_no for each group_id. I’m using this query:

SELECT MAX(item_no)
  OVER (PARTITION BY group_id)
FROM my_table;

I need only one record because I’m embedding this query in a CASE WHEN statement to apply logic based on whether or not item_no is the highest value per group.

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

Desired Output:

2

Actual Output:

2
2

How do I modify my query to only output one record with the maximum item_no per group_id?

>Solution :

Use an aggregate function along with GROUP BY instead an window function.

A window function, also known as an analytic function, computes values over a group of rows and returns a single result for each row. This is different from an aggregate function, which returns a single result for a group of rows.

SELECT group_id, MAX(item_no)
  FROM my_table
 GROUP BY group_id;
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