如何生成月度报告,用零填充一个月中缺少的几天
How to generate a monthly report filling missing days of the month with zero
假设我在 QuestDB table 上有以下数据:
ts | item
------------------------
2020-01-02T10:12 | a
2020-01-02T10:20 | b
2020-01-03T11:20 | a
2020-01-03T11:30 | b
2020-01-03T11:40 | c
我可以执行以下查询来计算特定月份按天采样的不同项目:
SELECT DAY(ts) as day, COUNT_DISTINCT(item) AS count_items
FROM my_table
WHERE ts IN '2020-01'
SAMPLE BY d FILL(0);
我得到以下数据:
day | count_items
------------------
2 | 2
3 | 3
我想要一个完整的月度报告而不是那个结果(即使是 table 没有数据并用零填充的日子)如下所示:
day | count_items
------------------
1 | 0
2 | 2
3 | 3
4 | 0
5 | 0
6 | 0
...
31 | 0
产生这种结果的最佳方法是什么?我一直在考虑将 JOIN 与 table 一起使用,它会生成特定月份的所有日期,但 QuestDB 没有实现 LEFT JOIN。
是否存在使用 QuestDB 生成此类报告的简单方法?
你可以用左连接
SELECT x as day, COALESCE(sb.count_items, 0) AS count_items
from long_sequence(31) ls
LEFT JOIN (
SELECT DAY(ts) as day, COUNT_DISTINCT(item) AS count_items
FROM my_table
WHERE ts IN '2020-01'
SAMPLE BY d
) AS sb ON sb.day = ls.x
我已经修改了 Alex 的答案,添加了一个 CAST(DAY(ts) AS LONG)
(如果没有这个,左连接条件中会出现类型错误)并使用 DAYS_IN_MONTH
函数:
SELECT x as day, COALESCE(sb.count_items, 0) AS count_items
from long_sequence(DAYS_IN_MONTH('2020-01') ls
LEFT JOIN (
SELECT CAST(DAY(ts) AS LONG) as day, COUNT_DISTINCT(item) AS count_items
FROM my_table
WHERE ts IN '2020-01'
SAMPLE BY d
) AS sb ON sb.day = ls.x
假设我在 QuestDB table 上有以下数据:
ts | item
------------------------
2020-01-02T10:12 | a
2020-01-02T10:20 | b
2020-01-03T11:20 | a
2020-01-03T11:30 | b
2020-01-03T11:40 | c
我可以执行以下查询来计算特定月份按天采样的不同项目:
SELECT DAY(ts) as day, COUNT_DISTINCT(item) AS count_items
FROM my_table
WHERE ts IN '2020-01'
SAMPLE BY d FILL(0);
我得到以下数据:
day | count_items
------------------
2 | 2
3 | 3
我想要一个完整的月度报告而不是那个结果(即使是 table 没有数据并用零填充的日子)如下所示:
day | count_items
------------------
1 | 0
2 | 2
3 | 3
4 | 0
5 | 0
6 | 0
...
31 | 0
产生这种结果的最佳方法是什么?我一直在考虑将 JOIN 与 table 一起使用,它会生成特定月份的所有日期,但 QuestDB 没有实现 LEFT JOIN。
是否存在使用 QuestDB 生成此类报告的简单方法?
你可以用左连接
SELECT x as day, COALESCE(sb.count_items, 0) AS count_items
from long_sequence(31) ls
LEFT JOIN (
SELECT DAY(ts) as day, COUNT_DISTINCT(item) AS count_items
FROM my_table
WHERE ts IN '2020-01'
SAMPLE BY d
) AS sb ON sb.day = ls.x
我已经修改了 Alex 的答案,添加了一个 CAST(DAY(ts) AS LONG)
(如果没有这个,左连接条件中会出现类型错误)并使用 DAYS_IN_MONTH
函数:
SELECT x as day, COALESCE(sb.count_items, 0) AS count_items
from long_sequence(DAYS_IN_MONTH('2020-01') ls
LEFT JOIN (
SELECT CAST(DAY(ts) AS LONG) as day, COUNT_DISTINCT(item) AS count_items
FROM my_table
WHERE ts IN '2020-01'
SAMPLE BY d
) AS sb ON sb.day = ls.x