Question

I have tried IsNull, Case statements and searched online, but for some reason if no records are found it still doesn't show a record or replace it with a '0' I'm trying to get all of the Types from the table and display how many have been done within a date range.

Here is my code so far.

SELECT     ISNULL(COUNT(Type), 0) AS Total, Type
FROM         dbo.Refs
WHERE     (DateSubmitted BETWEEN CONVERT(DATETIME, '2014-02-01 00:00:00', 102) AND CONVERT(DATETIME, '2015-01-01 00:00:00', 102))
GROUP BY Type

The Type column is a varchar to unfortunaltey

Thanks

Was it helpful?

Solution

If you have a table that stores your types you can use:

SELECT  COUNT(r.Type) AS Total, t.Type
FROM    TypeTable t
        LEFT JOIN dbo.Refs r
            ON r.Type = t.Type 
            AND r.DateSubmitted >= CONVERT(DATETIME, '2014-02-01 00:00:00', 102) 
            AND r.DateSubmitted <=  CONVERT(DATETIME, '2015-01-01 00:00:00', 102)
GROUP BY t.Type;

Otherwise you will need to use your existing table to get a list of all types, before joining to the table filtered by date:

SELECT  COUNT(r.Type) AS Total, t.Type
FROM    (SELECT DISTINCT Type FROM dbo.Refs) t
        LEFT JOIN dbo.Refs r
            ON r.Type = t.Type 
            AND r.DateSubmitted >= CONVERT(DATETIME, '2014-02-01 00:00:00', 102) 
            AND r.DateSubmitted <=  CONVERT(DATETIME, '2015-01-01 00:00:00', 102)
GROUP BY t.Type;

Alternatively you could use:

SELECT  COUNT(CASE WHEN r.DateSubmitted >= CONVERT(DATETIME, '2014-02-01 00:00:00', 102) 
                        AND r.DateSubmitted <=  CONVERT(DATETIME, '2015-01-01 00:00:00', 102) 
                    THEN 1
                END) AS Total, 
        t.Type
FROM    dbo.Refs r
GROUP BY r.Type;

The best method will depend on your indexes/if you do or don't have a table to store all types.

OTHER TIPS

you cannot use a group by to achieve what you want -See the following post Count Returning blank instead of 0

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top