Counting null and non-null values in a single query

后端 未结 26 1086
星月不相逢
星月不相逢 2021-01-29 19:31

I have a table

create table us
(
 a number
);

Now I have data like:

a
1
2
3
4
null
null
null
8
9

Now I need

26条回答
  •  孤独总比滥情好
    2021-01-29 19:57

    This works in T-SQL. If you're just counting the number of something and you want to include the nulls, use COALESCE instead of case.

    IF OBJECT_ID('tempdb..#us') IS NOT NULL
        DROP TABLE #us
    
    CREATE TABLE #us
        (
        a INT NULL
        );
    
    INSERT INTO #us VALUES (1),(2),(3),(4),(NULL),(NULL),(NULL),(8),(9)
    
    SELECT * FROM #us
    
    SELECT CASE WHEN a IS NULL THEN 'NULL' ELSE 'NON-NULL' END AS 'NULL?',
            COUNT(CASE WHEN a IS NULL THEN 'NULL' ELSE 'NON-NULL' END) AS 'Count'
        FROM #us
        GROUP BY CASE WHEN a IS NULL THEN 'NULL' ELSE 'NON-NULL' END
    
    SELECT COALESCE(CAST(a AS NVARCHAR),'NULL') AS a,
            COUNT(COALESCE(CAST(a AS NVARCHAR),'NULL')) AS 'Count'
        FROM #us
        GROUP BY COALESCE(CAST(a AS NVARCHAR),'NULL')
    

提交回复
热议问题