警告:在Aqua Data Studio中,空值由集合或其他SET操作消除
数据为空时出现问题,显示结果时出现警告。 如何解决这个问题呢?。 当表中没有数据时如何将空数据更改为0?
这是我的代码:
SELECT DISTINCT c.username AS assigner_officer, d.description AS ticketcategory, (SELECT Count(closed) FROM ticket WHERE assigned_to = c.user_id AND closed IS NOT NULL GROUP BY assigned_to)closedcases, (SELECT Count(closed) FROM ticket WHERE assigned_to = c.user_id AND closed IS NULL GROUP BY assigned_to)opencases FROM ticket a JOIN ticketlog b ON a.ticketid = b.ticketid JOIN access c ON a.assigned_to = c.user_id JOIN ticket_category d ON a.cat_code = d.id JOIN lookup_department e ON a.department_code = e.code
结果如下所示:
Warnings: ---> W (1): Warning: Null value is eliminated by an aggregate or other SET operation. <--- assigner_officer ticketcategory closedcases opencases ------------------- ----------------- -------------- ------------ abdulhafiz Enquiry (null) 0 affan Enquiry 12 (null) amirul Enquiry 1 (null) azrul_fahmi Enquiry 45 0 Azwani Enquiry (null) 0 chai Enquiry 4 (null) dalinawati Enquiry 1 0 Emmy Complaints (null) 0 Fadhlia Enquiry 38 0 fairulhalif Others 1 (null) farikh Enquiry (null) 0 ismailh Enquiry 28 0 izzahanna Enquiry (null) 0 Kamsuzilawati Enquiry 1 (null)
您将主要使用COUNT
来通过UID进行汇总。 因此
COUNT([uid])
会产生警告:
警告:空值由集合或其他SET操作消除。
同时与左连接一起使用,其中计数的对象不存在。
在这种情况下使用COUNT(*)
也会导致不正确的结果,因为您将计算存在的结果总数(即父项)。
使用COUNT([uid])
是一种有效的计数方式,警告只不过是一个警告。 但是,如果您担心,而且您希望在这种情况下获得真正的uid数,那么您可以使用:
SUM(CASE WHEN [uid] IS NULL THEN 0 ELSE 1 END) AS [new_count]
这不会增加大量的开销到您的查询。 (testing的mssql 2008)
解决这个问题的一个办法就是closures警告。
SET ANSI_WARNINGS OFF; GO
使用ISNULL(field, 0)
它也可以用于聚合:
ISNULL(count(field), 0)
但是,您可能会考虑更改count(field) to count(*)
编辑:
尝试:
closedcases = ISNULL( (select count(closed) from ticket where assigned_to = c.user_id and closed is not null group by assigned_to), 0), opencases = ISNULL( (select count(closed) from ticket where assigned_to = c.user_id and closed is null group by assigned_to), 0),
你想把ISNULL
放在COUNT
函数里面,而不是在外面:
不好: ISNULL(COUNT(field), 0)
GOOD: COUNT(ISNULL(field, 0))
如果集合函数内存在任何空值,则将面临此问题。 而不是下面的代码
SELECT Count(closed) FROM ticket WHERE assigned_to = c.user_id AND closed IS NULL
使用像
SELECT Count(ISNULL(closed, 0)) FROM ticket WHERE assigned_to = c.user_id AND closed IS NULL