I am trying to get a COUNT
where a certain column should have at least a value. If this column has EMPTY
or NULL
value, this should not be included in the COUNT
. The problem is, I've tried many different SQL functions (eg: IS NOT NULL
, <>
, LTRIM
, RTRIM
, etc...) but rows that don't have values are still included in the count.
For example; in the database I have a column called MYDESCRIPTION
. There are four records in the table. Two of them have a value in the MYDESCRIPTION
column, two of them don't. When I look for a count for those that have a value, the other two that don't have are still included in the result. So it is still showing four.
Here are some sample queries within a specific day:
SELECT COUNT(*)
FROM TABLE
WHERE DATE (CREATIONDATE) >= '2014-12-01' AND
DATE (CREATIONDATE) <= '2014-12-01' AND
MYDESCRIPTION <> ''
And
SELECT COUNT(*)
FROM TABLE
WHERE DATE (CREATIONDATE) >= '2014-12-01' AND
DATE (CREATIONDATE) <= '2014-12-01' AND
MYDESCRIPTION IS NOT NULL
These two simple queries are just some that I have tried. I suppose the query is still counting the column that has no value as it seems like it has a value.
Your WHERE clause should most likely look like:
WHERE DATE (CREATIONDATE) = '2014-12-01'
AND MYDESCRIPTION IS NOT NULL
AND MYDESCRIPTION <> ''
SELECT COUNT(*) FROM TABLE
WHERE DATE (CREATIONDATE) >= '2014-12-01'
AND DATE (CREATIONDATE) <= '2014-12-01'
AND (MYDESCRIPTION IS NOT NULL and MYDESCRIPTION <> '')
You can use SUM(CASE...) for situations like this. Adjust the syntax as needed for your DBMS.
SELECT
SUM(CASE WHEN LENGTH(MYDESCRIPTION) = 0 THEN 0 ELSE 1) END) AS "Non-Nulls"
FROM TABLE
WHERE DATE (CREATIONDATE) >= '2014-12-01' AND
DATE (CREATIONDATE) <= '2014-12-01' AND
MYDESCRIPTION IS NOT NULL
Try this:
SELECT COUNT (*)
FROM
(SELECT * FROM TABLE
WHERE 1=1
AND (CAST (CREATIONDATE AS DATE) BETWEEN CAST('2014-12-01' AS DATE) AND CAST('2014-12-01' AS DATE) )
AND (MYDESCRIPTION IS NOT NULL AND LENGTH(TRIM(MYDESCRIPTION)) > 0 )
)
SELECT COUNT(*) FROM TABLE
WHERE DATE (CREATIONDATE) >= '2014-12-01'
AND DATE (CREATIONDATE) <= '2014-12-01'
AND (MYDESCRIPTION IS NOT NULL and RTRIM(MYDESCRIPTION) <> '')
IS NOT NULL
is a different condition from <> ''
.
IS NOT NULL
means the value is unknown.
<> ''
means the value is not equal to a ZLS, or Zero Length String.
In adding the RTRIM
, I was eliminating the possibility of a CHAR
or NCHAR
field that was equal to a bunch of spaces, which may or may not be desirable in this OP's question.
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.