这是我遇到的问题的摘要版本,但是遇到问题的结果。真正的问题涉及巨大的UNION月度数据表组,但SQL将是巨大的,并没有添加任何内容。所以:
SELECT entity_id,
sum(day_call_time) as day_call_time
from (
SELECT entity_id,
sum(answered_day_call_time) as day_call_time
FROM XCDRDNCSum201108
where (day_of_the_month >= 10 AND day_of_the_month<=24)
and LPAD(core_range,4,"0")="0987"
and LPAD(subrange,3,"0")="654"
and SUBSTR(LPAD(core_number,7,"0"),4,7)="3210"
) as summary
是问题:当子查询XCDRDNCSum201108中的表没有返回任何行时,因为它是一个总和,列值包含null。并且entity_id是主键的一部分,不能为null。 如果我取出总和,只查询entity_id,子查询不包含任何行,因此外部查询不会失败,但是当我使用sum时,我得到错误1048列'entity_id'不能为空
我该如何解决这个问题?有时候没有数据。
答案 0 :(得分:2)
你完全过度了解查询...在内部预先求和,然后再在外面求和。此外,我知道您不是DBA,但如果您正在进行聚合,则通常需要按其分组的条件。在此处显示的情况下,您将获得所有实体ID的调用总和。因此,您必须拥有任何非聚合的组。但是,如果您关心的是Grand total而不考虑entity_ID,那么您可以跳过该组,但也不会包含实际的实体ID ......
如果您希望包含显示每个特定实体ID的实际时间......
SELECT
entity_id,
sum(answered_day_call_time) as day_call_time,
count(*) number_of_calls
FROM
XCDRDNCSum201108
where
(day_of_the_month >= 10 AND day_of_the_month<=24)
and LPAD(core_range,4,"0")="0987"
and LPAD(subrange,3,"0")="654"
and SUBSTR(LPAD(core_number,7,"0"),4,7)="3210"
group by
entity_id
这会导致类似(虚构数据)
Entity_ID Day_Call_Time Number_Of_Calls
1 10 3
2 45 4
3 27 2
如果您关心的是总通话时间
SELECT
sum(answered_day_call_time) as day_call_time,
count(*) number_of_calls
FROM
XCDRDNCSum201108
where
(day_of_the_month >= 10 AND day_of_the_month<=24)
and LPAD(core_range,4,"0")="0987"
and LPAD(subrange,3,"0")="654"
and SUBSTR(LPAD(core_number,7,"0"),4,7)="3210"
这会导致类似(虚构数据)
Day_Call_Time Number_Of_Calls
82 9
答案 1 :(得分:0)
会:
sum(answered_day_call_time) as day_call_time
更改为
ifnull(sum(answered_day_call_time),0) as day_call_time
工作?我在这里假设mysql,但是coalesce函数也应该起作用。