SQL 汇总计数显示总计为 NULL
SQL Count with rollup shows totals as NULL
我需要知道如何用总数替换 NULL。
这是我使用 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
这是输出:
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
我喜欢用 'Total' 替换“NULL”值:(如下所示)
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
任何将 NULL 转换为单词 TOTAL 的建议都将不胜感激。
我一般只用coalesce()
:
SELECT COALESCE(DATENAME(YEAR, study_date), 'Total') AS Year,
COUNT(distinct study_uid) AS 'Studies'
FROM local_studies
GROUP BY rollup (DATENAME(YEAR, study_date))
ORDER BY Year DESC;
请注意,这将切换为使用 DATENAME()
,因此该列是字符串而不是数字。
此外,如果值可能是 NULL
,则效果不佳。为此,有 GROUPING()
函数。
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;
我需要知道如何用总数替换 NULL。
这是我使用 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
这是输出:
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
我喜欢用 'Total' 替换“NULL”值:(如下所示)
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
任何将 NULL 转换为单词 TOTAL 的建议都将不胜感激。
我一般只用coalesce()
:
SELECT COALESCE(DATENAME(YEAR, study_date), 'Total') AS Year,
COUNT(distinct study_uid) AS 'Studies'
FROM local_studies
GROUP BY rollup (DATENAME(YEAR, study_date))
ORDER BY Year DESC;
请注意,这将切换为使用 DATENAME()
,因此该列是字符串而不是数字。
此外,如果值可能是 NULL
,则效果不佳。为此,有 GROUPING()
函数。
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;