简体   繁体   中英

SQL: Replacing NULL with 0 in monthly count table

I have a table named GAINLP The table contains fields

'Record#"           (INT), 
'SightingDate'      (DATE), 
'SpeciesName'       (VARCHAR)

Need SQL to output an array that contains an integer that corresponds to the sum of SightingDate for each month.

Example : 0,0,0,0,1,5,10,12,5,3,0,0

Instead, the following code causes null value sums to be skipped and I'm left with 1,5,10,12,5,3

`select count(SightingDate) from GAINLP where SpeciesName LIKE '%Actias luna' GROUP BY MONTH(SightingDate)`

I understand that this can be done by joining with a calendar table, but I've not found examples of such code that also employs the WHERE operator.

You seem to be looking for conditional aggregation. The principle is to move the filtering logic to a CASE construct within the aggregate function.

SELECT 
    SUM(
        CASE
            WHEN SpeciesName LIKE '%Actias luna'
                THEN 1 
            ELSE 0
        END
    )
GROM gainlp 
GROUP BY MONTH(SightingDate)

You could use conditional aggregation here:

SELECT
    MONTH(SightingDate) AS month,
    COUNT(CASE WHEN SpeciesName LIKE '%Actias luna' THEN 1 END) cnt
FROM GAINLP
GROUP BY
    MONTH(SightingDate);

But, this might not be as efficient as a calendar table based join approach. Here is how you might do that:

SELECT
    t1.month,
    COUNT(t2.SightingDate) cnt
FROM (SELECT DISTINCT MONTH(SightingDate) AS month FROM GAINLP) t1
LEFT JOIN GAINLP t2
    ON t1.month = MONTH(t2.SightingDate)
WHERE
    t2.SpeciesName LIKE '%Actias luna'
GROUP BY
    t1.month;

Note: It might be possible that your data could span more than a given year, in which case you would probably want to report both the year and month.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM