Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a query Count() return 0 instead of empty

I have a report that tracks how long certain items have been in the database, and does so by tracking it over a series of age ranges (20-44, 45-60, 61-90, 91-180, 180+). I have the following query as the data source of the report:

SELECT DISTINCT Source.ItemName, 
Count(SELECT Source.DateAdded FROM Source WHERE Int(Date()-Source.DateAdded) > 20) AS Total, 
Count(SELECT Source.DateAdded FROM Source WHERE Int(Date()-Source.DateAdded) BETWEEN 20 AND 44) AS BTWN_20_44, 
Count(SELECT Source.DateAdded FROM Source WHERE Int(Date()-Source.DateAdded) BETWEEN 45 AND 60) AS BTWN_45_60, 
Count(SELECT Source.DateAdded FROM Source WHERE Int(Date()-Source.DateAdded) BETWEEN 61 AND 90) AS BTWN_61_90, 
Count(SELECT Source.DateAdded FROM Source WHERE Int(Date()-Source.DateAdded) BETWEEN 91 AND 180) AS BTWN_91_180, 
Count(SELECT Source.DateAdded FROM Source WHERE Int(Date()-Source.DateAdded) > 180) AS GT_180
FROM Source
GROUP BY Source.ItemName;

This query works great, except if there aren't any entries a column. Instead of returning a count of 0, an empty value is returned.

How do I get Count() to return a 0 instead of empty?

like image 901
Andrew Scagnelli Avatar asked May 31 '26 13:05

Andrew Scagnelli


2 Answers

You can return

ISNULL(Count(......), 0)

and all should be fine - would be in MS SQL Server - but I just saw you're using Access. Since I don't know Access enough, I'm not sure this will work - can you try it?

OK - glad to see there's something similar in Access (if not exactly the same as in SQL Server).

Marc

like image 170
marc_s Avatar answered Jun 03 '26 01:06

marc_s


On second though (without more information) I think you are doing this query very wrong....

As I said, when I try your original query I get an error "At most one record can be returned by this subquery".

This is probably a little closer to what you want

SELECT DISTINCT Source.ItemName, 
    (SELECT count(Source.DateAdded ) FROM Source 
        WHERE Int(Date()-Source.DateAdded)> 20)  AS Total, 
    (SELECT count(Source.DateAdded ) FROM Source  
        WHERE Int(Date()-Source.DateAdded) BETWEEN 20 AND 44) AS BTWN_20_44, 
    (SELECT count(Source.DateAdded ) FROM Source  
        WHERE Int(Date()-Source.DateAdded) BETWEEN 45 AND 60) AS BTWN_45_60, 
    (SELECT count(Source.DateAdded ) FROM Source  
        WHERE Int(Date()-Source.DateAdded) BETWEEN 61 AND 90) AS BTWN_61_90, 
    (SELECT count(Source.DateAdded ) FROM Source  
        WHERE Int(Date()-Source.DateAdded) BETWEEN 91 AND 180) AS BTWN_91_180, 
    (SELECT count(Source.DateAdded ) FROM Source  
        WHERE Int(Date()-Source.DateAdded) > 180) AS GT_180
FROM Source
GROUP BY Source.ItemName;

Unless you are trying to get a count per Item name... in which case it's a little trickyier.

like image 43
BIBD Avatar answered Jun 03 '26 03:06

BIBD