Counting null and non-null values in a single query

后端 未结 26 1075
星月不相逢
星月不相逢 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:49

    I had a similar issue: to count all distinct values, counting null values as 1, too. A simple count doesn't work in this case, as it does not take null values into account.

    Here's a snippet that works on SQL and does not involve selection of new values. Basically, once performed the distinct, also return the row number in a new column (n) using the row_number() function, then perform a count on that column:

    SELECT COUNT(n)
    FROM (
        SELECT *, row_number() OVER (ORDER BY [MyColumn] ASC) n
        FROM (
            SELECT DISTINCT [MyColumn]
                        FROM [MyTable]
            ) items  
    ) distinctItems
    

提交回复
热议问题