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 use MAX in CTE using SQL

I’m attempting to use a CTE and a MAX function to find the highest number in a grouping of countries. Ultimately in this table trying to find the total number of vaccinations for each country listed by summing the "new vaccines" . Here’s my code so far:

WITH VacGDP (Location, gdp_per_capita, Total_Shots)
as
(
SELECT Location, CovidVaccinations.gdp_per_capita, SUM(cast(New_vaccinations as bigint)) as Total_Shots
FROM CovidVaccinations
WHERE Continent is not null
GROUP BY Location, gdp_per_capita, New_vaccinations
)
SELECT Location, MAX(Total_Shots) as Total_Shots
FROM VacGDP
GROUP BY Location, Total_Shots
ORDER BY Location, Total_Shots DESC

This gives the following table:
|Location|Total_Shots|
|:—-|:—–:|
|Afghanistan|6868|
|Afghanistan|4015|
|Afghanistan|2859|
|Afghanistan|NULL|

I’m ultimately trying to just have one row showing Afghanistan 6868, so one row per country in this database.

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

I’m sure this is something super easy to fix but I’m a bit lost!

>Solution :

  • Remove New_Vaccinations from your CTE group by
  • Remove total_shots from your group and order by.

Also you mention you want to see per day but there are no date filters/indicators in your code?

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