gpt4 book ai didi

sql - Postgresql - 分组依据

转载 作者:行者123 更新时间:2023-12-03 18:43:14 25 4
gpt4 key购买 nike

我有一个简单的 groupby 场景。下面是查询的输出。
enter image description here
查询是:select target_date, type, count(*) from table_name group by target_date, type查询和输出非常好。
我的问题是我在 Grafana 中使用它进行绘图。那是以 postgres 作为后端的 Grafana。
发生的情况是因为在 01-10-2020 和 03-10-2020 错过了“type2”类别,因此根本不会绘制 type2 类别(左右条形图)。虽然“type2”在其他日子里存在。
它期待一些类似的东西
enter image description here
因此,每当日期中缺少某个类别时,我们都需要一个值为 0 的计数。
需要在查询中处理此问题,因为无法修改源数据。
任何帮助在这里表示赞赏。

最佳答案

您可以在此处使用日历表方法:

SELECT
t1.target_date,
t2.type,
COUNT(t3.target_date) AS count
FROM (SELECT DISTINCT target_date FROM yourTable) t1
CROSS JOIN (SELECT DISTINCT type FROM yourTable) t2
LEFT JOIN yourTable t3
ON t3.target_date = t1.target_date AND
t3.type = t2.type
GROUP BY
t1.target_date,
t2.type
ORDER BY
t1.target_date,
t2.type;
这里的想法是交叉连接子查询以查找所有不同的目标日期和类型,以生成查询的起点。然后,我们将这个中间表连接到您的实际表,并找到每个日期和类型的计数。

关于sql - Postgresql - 分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64586581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com