Search code examples
sqlsql-serverrollup

SQL Count with rollup shows totals as NULL


I need to know how I can replace the NULL with total.

Here is a copy of my query using ROLLUP.

SELECT    DATEPART(YEAR, study_date) AS 'Year',
          COUNT(distinct study_uid) AS 'Studies'
FROM local_studies
GROUP BY rollup (DATEPART(YEAR, study_date))
ORDER BY  'Year' DESC

This is the output:

  Year  Studies
2020    497
2019    165743
2018    165043
2017    182712
2016    210700
2015    219373
2014    214097
2013    211566
2012    212900
2011    217957
2010    213542
2009    193510
2008    95434
2007    53722
2006    44422
2005    12119
2004    129
2003    65
2000    4
NULL    2413535

I like to see the 'NULL" value replace with 'Total': (as shown below)

  Year  Studies
2020    497
2019    165743
2018    165043
2017    182712
2016    210700
2015    219373
2014    214097
2013    211566
2012    212900
2011    217957
2010    213542
2009    193510
2008    95434
2007    53722
2006    44422
2005    12119
2004    129
2003    65
2000    4
Total   2413535

Any advice for converting that NULL to the word TOTAL would be greatly appreciated.


Solution

  • SELECT    CASE GROUPING_ID(DATEPART(YEAR, study_date)) WHEN 1 THEN 'Total' ELSE CAST(DATEPART(YEAR, study_date) AS VARCHAR(10)) END AS 'Year',
              COUNT(distinct study_uid) AS 'Studies'
    FROM local_studies
    GROUP BY rollup (DATEPART(YEAR, study_date))
    ORDER BY  GROUPING_ID(DATEPART(YEAR, study_date)), 'Year' DESC;