[英]IsNull not returning 0 on SQL query
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. 我已经尝试过IsNull,Case语句并在线搜索,但出于某种原因,如果没有找到记录,它仍然没有显示记录或用'0'替换它我试图从表中获取所有类型显示在日期范围内完成的数量。
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 Type列是一个不幸的varchar
Thanks 谢谢
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. 最好的方法取决于您的索引/如果您有或没有表来存储所有类型。
你不能使用group by来实现你想要的东西 - 参见以下帖子计数返回空白而不是0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.