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

sql getting the minimum and maximum result in same query

From the years table below, how would I be able to get the rows which have the minimum and maximum years? For example, the minimum year in the years table is 1776 and the maximum year is 2021. Therefore, the resulting table should have the row with the year 1776 and the 3 rows with 2021.

Years table

+--------+------+
| name   | year |
+--------+------+
| name 1 | 1776 |
| name 2 | 1905 |
| name 3 | 2000 |
| name 4 | 2021 |
| name 5 | 2021 |
| name 6 | 2021 |
+--------+------+

Desired result

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

    +--------+------+
    | name   | year |
    +--------+------+
    | name 1 | 1776 |
    | name 4 | 2021 |
    | name 5 | 2021 |
    | name 6 | 2021 |
    +--------+------+

>Solution :

Find the minimum and maximum year and joined it to the main table

SELECT name,year
FROM

  (SELECT min(year) AS min_year,MAx(year) AS max_year
   FROM years) t1
JOIN years t2 ON t1.min_year = t2.year OR t1.max_year = t2.year

db<>fiddle

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