我有一个三个mysql数据库表,其中包含客户公司的通话记录。我想每小时从公司组的数据库中获取数据。如果一小时没有数据,则应返回零。
我正在执行此查询,但是只获得了数据库中存在数据的那小时的结果。
这是我的疑问。
select ph_Plans.Comp_ID, Plan_Type, ph_Companies.CompanyName,
(sum(call_length_billable)*100)/(Plan_Limit*60) as total,
hour(calldate)
from ph_Plans
join ph_Companies
on ph_Companies.Comp_ID = ph_Plans.Comp_ID
join cdr
on cdr.CompanyName = ph_Companies.CompanyName
where Plan_Type='Per_Min'
and date(calldate)='2012-10-01'
and ph_Companies.CompanyName='"ReadySpace-EN"'
group by hour(calldate);
这是我得到的结果。
+---------+-----------+-----------------+--------+----------------+
| Comp_ID | Plan_Type | CompanyName | total | hour(calldate) |
+---------+-----------+-----------------+--------+----------------+
| 44 | Per_Min | "ReadySpace-EN" | 3.7467 | 1 |
| 44 | Per_Min | "ReadySpace-EN" | 9.4933 | 18 |
| 44 | Per_Min | "ReadySpace-EN" | 1.6600 | 20 |
| 44 | Per_Min | "ReadySpace-EN" | 3.7333 | 21 |
| 44 | Per_Min | "ReadySpace-EN" | 4.6067 | 2 |
| 44 | Per_Min | "ReadySpace-EN" | 7.6533 | 23 |
+---------+-----------+-----------------+--------+----------------+
但我希望结果从第0小时到23小时。如果没有数据,那么它应该返回零。
答案 0 :(得分:1)
执行JOIN
时,只有JOIN
表上的数据都与要加入的列对应的数据。当你仍然想要在另一个表中没有相应数据的结果时,你想要做的是LEFT JOIN
。
这样的事情:
select ph_Plans.Comp_ID, Plan_Type, ph_Companies.CompanyName,
if(call_length_billable IS NULL, 0, (sum(call_length_billable)*100)/(Plan_Limit*60)) as total,
ifnull(hour(calldate), 0) hour
from ph_Plans
left join ph_Companies
on ph_Companies.Comp_ID = ph_Plans.Comp_ID
left join cdr
on cdr.CompanyName = ph_Companies.CompanyName
where Plan_Type='Per_Min'
and (date(calldate)='2012-10-01' OR calldate IS NULL)
and (ph_Companies.CompanyName='"ReadySpace-EN"' OR ph_Companies.CompanyName IS NULL)
group by hour(calldate);
答案 1 :(得分:0)
有两种方法可以产生0到23小时。你可以在这个演示中找到它们。
使用INFORMATION_SCHEMA.COLLATION_CHARACTER_SET_APPLICABILITY
如果我们使用最典型的方法,那就是使用临时表与表连接。 鉴于以下假设,请将此连接到您的主要查询。
示例查询:
SELECT COALESCE(P.ID,0),
COALESCE(P.CALLDATE,0),
COALESCE(HOUR(P.CALLDATE),0)
FROM NUMBERS A
LEFT JOIN
PLAN P
ON A.N = HOUR(P.CALLDATE)
GROUP BY A.N
;
结果:
| COALESCE(P.ID,0) | COALESCE(P.CALLDATE,0) | COALESCE(HOUR(P.CALLDATE),0) |
----------------------------------------------------------------------------
| 0 | 0 | 0 |
| 1 | 2013-01-03 01:11:14 | 1 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 4 | 2013-01-03 09:51:02 | 9 |
| 3 | 2013-01-03 10:50:20 | 10 |
| 2 | 2013-01-03 11:31:24 | 11 |
| 5 | 2013-01-03 12:30:00 | 12 |
| 6 | 2013-01-03 13:41:01 | 13 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 7 | 2013-01-03 16:19:08 | 16 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 8 | 2013-01-03 20:18:30 | 20 |
| 0 | 0 | 0 |
| 10 | 2013-01-04 22:21:50 | 22 |
| 9 | 2013-01-03 23:01:44 | 23 |
由于您已经显示了从表生成的结果,因此我使用相同的查询来连接0-23小时数据表。另外,在上面的演示中似乎没有完整的表架构来创建它们。此外,没有提到哪个表格包含列calldate
,因此我认为它位于 Plan_Type
表中。