Search code examples
sqlsortingunion-all

Achieving Tabular Pivot Type report in SQL


I have the below code which I am trying to get the info of Population of City, County Total for those cities and State Total for all counties in the state. I was able to crack most of it except the State sorting or in genaral State sorting.


ORDER BY State, County, SortOrder, City, Population

Can someone help to check and recommend sorting changes to get the correct output? Let me know if you have any questions.


Solution

  • This looks like an ideal opportunity to use grouping sets.

    You can express all these queries as a single query with the following grouping sets:

    select State, 
      Coalesce(County, 'State Total:')  County,
      Coalesce(City, case when County is null then '' end, 'County Total:') City,
      Sum(Population) Population
    from t
    group by grouping sets(
      (State, County, City), 
      (State, County), 
      (State)
    )
    order by State, 
      case when County = 'State Total:' then 1 end, 
      case when City = 'County Total:' then 1 end;
    

    See a demo Fiddle

    And output:

    enter image description here