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 take particular number for each group

I have the following table sport statistic table:

enter image description here

I would like 10 last records from the table for each team and then analyze and aggregate them.

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

Totally, I have 12 records for each team. But I want to analyze 10 only. I have the following SQL query

select
       guest_team_id,
       home_team_id,
       count(drawn)          drawn_count,
       count(home_team_lost) home_team_lost_count,
       count(home_team_won)  home_team_won_count,
       count(*) total
from statistic_records
group by home_team_id, guest_team_id;

with the following result
enter image description here

and have no idea how to limit records quantity for each team.

Any ideas?

>Solution :

I think you can use Analytical function to achieve that –

SELECT guest_team_id,
       home_team_id,
       count(drawn)          drawn_count,
       count(home_team_lost) home_team_lost_count,
       count(home_team_won)  home_team_won_count,
       count(*) total
from (SELECT *, ROW_NUMBER() OVER(PARTITION BY home_team_id ORDER BY id) rn
        FROM statistic_records)
WHERE rn <= 10
group by home_team_id, guest_team_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