我有一个mysql查询,有时会导致缺少值。对于我的仪表板,我想填写这些值,但如果可以的话,我希望避免建立虚拟表。
查询:
SELECT COUNT(Comms_Timestamp) as call_count,DAYOFWEEK(Comms_Timestamp) as bucket
FROM tblTest GROUP BY bucket;
产生
+------------+--------+
| call_count | bucket |
+------------+--------+
| 4 | 1 |
| 7 | 2 |
| 7 | 3 |
| 1 | 5 |
| 6 | 6 |
| 1 | 7 |
+------------+--------+
在上面的示例中,您可以看到存储桶4丢失。我考虑了连接到选择联合数组的方法,但是由于这两个字段都是聚合的,因此我不确定该如何处理。
测试数据为
+---------------------+
| Comms_Timestamp |
+---------------------+
| 2018-12-24 06:04:05 |
| 2018-12-24 12:18:39 |
| 2018-12-21 04:24:31 |
| 2018-12-21 08:32:44 |
| 2018-12-30 01:41:06 |
| 2018-12-30 01:53:00 |
| 2018-12-30 01:53:39 |
| 2018-12-30 02:00:01 |
| 2018-12-17 15:55:03 |
| 2018-12-17 16:04:12 |
| 2018-12-17 16:05:41 |
| 2018-12-17 16:07:43 |
| 2018-12-17 16:10:25 |
| 2018-12-18 14:03:22 |
| 2018-12-18 14:03:29 |
| 2018-12-18 14:10:19 |
| 2018-12-18 14:10:29 |
| 2018-12-18 14:10:31 |
| 2018-12-18 14:10:47 |
| 2018-12-18 14:10:55 |
| 2018-12-20 08:21:07 |
| 2018-12-28 11:03:59 |
| 2018-12-28 12:06:40 |
| 2018-12-28 12:15:01 |
| 2018-12-28 14:29:24 |
| 2019-01-05 13:33:43 |
+---------------------+
答案 0 :(得分:1)
由于您使用的是mysql并且无权访问seq_
选项,因此这是另一种方法:
SELECT A.x AS bucket, IF(ISNULL(COUNT(t2.Comms_Timestamp)), 0, COUNT(t2.Comms_Timestamp)) AS call_count FROM
(select 1 x union select 2 union select 3 union select 4 union select 5 union select 6 union select 7) AS A
LEFT JOIN tblTest AS t2 ON DAYOFWEEK(t2.Comms_Timestamp) = A.x
GROUP BY bucket
ORDER BY bucket;
这可能不是最漂亮的选择,但可以满足您的需求。
这是一个数据库字段链接:db<>fiddle
答案 1 :(得分:0)
如果您使用的是MariaDB,则他们的Sequence Storage Engine
此表不需要创建,但是必须知道最大值。
select version();
| version() | | :------------------------------------------ | | 10.3.11-MariaDB-1:10.3.11+maria~stretch-log |
create table bob (a int)
✓
insert into bob values (4),(2)
✓
select * from seq_1_to_5
| seq | | --: | | 1 | | 2 | | 3 | | 4 | | 5 |
SELECT s.seq, bob.a FROM seq_1_to_5 s LEFT JOIN bob ON bob.a = s.seq ORDER BY s.seq
seq | a --: | ---: 1 | null 2 | 2 3 | null 4 | 4 5 | null
db <>提琴here
答案 2 :(得分:0)
您可以在MYSQL中使用IFNULL()函数:
SELECT IFNULL(COUNT(C.Comms_Timestamp),0) as call_count,IFNULL(DAYOFWEEK(C.Comms_Timestamp),0) as bucket
FROM tblCommunication as C LEFT JOIN tblCareTeam as CT on C.id_Case = CT.id_Case
GROUP BY CT.id_Site,bucket
HAVING CT.id_Site=8;