Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help counting different values in the same table in SQL

Tags:

sql

count

I'm new to SQL and I'm having trouble with a count query. I want to count the number of results that return a value and also return a second count if the value is null.

Here is what I have so far. If anyone can help I would appreciate it. Thanks.

Select
    Sum(Case When Column name = '!NULL' Then 1 Else 0 End) as [Policy ID],
    Sum(Case When Column name = 'NULL' Then 1 Else 0 End) as [No Policy Id]
    --Count(*) as [Total]
From 
    table.name
Where 
    columnname >= '2016-01-01'
like image 986
H80TW Avatar asked Sep 28 '26 00:09

H80TW


2 Answers

Use IS NULL and IS NOT NULL instead of checking nulls with equality:

SELECT
    SUM(CASE WHEN Column_name IS NOT NULL THEN 1 ELSE 0 END) AS [Policy ID],
    SUM(CASE WHEN Column_name IS NULL     THEN 1 ELSE 0 END) AS [No Policy Id]
--COUNT(*) AS [Total]
FROM table.name
WHERE columnname >= '2016-01-01'

In SQL the value NULL means "unknown" and hence comparing a column value against it using = also yields an unknown result. Instead, use IS NULL or IS NOT NULL.

like image 197
Tim Biegeleisen Avatar answered Sep 29 '26 14:09

Tim Biegeleisen


@TimBiegelesien's answer is right the only thing I would add/suggest would be if ColumnName contains an Empty string ('') and you want to count it as NULL you could do something like this:

Select
Sum(Case When LENGTH(ColumnName) > 0 Then 1 Else 0 End) as [Policy ID],
Sum(Case When LENGTH(ColumnName) < 1 Then 1 Else 0 End) as [No Policy Id]
--Count(*) as [Total]
From table.name
Where columnname >= '2016-01-01'

Note in some rdbms LENGTH is actually LEN

Select
Sum(Case When LEN(ColumnName) > 0 Then 1 Else 0 End) as [Policy ID],
Sum(Case When LEN(ColumnName) < 1 Then 1 Else 0 End) as [No Policy Id]
--Count(*) as [Total]
From table.name
Where columnname >= '2016-01-01'

This will still work even if the datatype is numeric (int, bigint, etc.)

like image 39
Matt Avatar answered Sep 29 '26 13:09

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!