gpt4 book ai didi

从子查询计算百分比的 SQL 查询

转载 作者:行者123 更新时间:2023-11-29 14:15:35 25 4
gpt4 key购买 nike

我有一张表:log

+----+---------------------+---------------+
| ID | Time | Status |
+----+---------------------+---------------+
| 1 | 2016-07-19 03:20:12 | 200 OK |
| 2 | 2016-07-20 05:20:12 | 404 NOT FOUND |
| 3 | 2016-07-19 00:00:00 | 200 OK |
| 4 | 2016-07-20 10:20:12 | 404 NOT FOUND |
| 5 | 2016-08-05 07:00:02 | 404 NOT FOUND |
+----+---------------------+---------------+

我需要按“404 NOT FOUND”状态组按日期顺序按总数百分比合并数据。 (下面)

理想的结果

+---------------------+---------+
| Date | Errors |
+---------------------+---------+
| 2016-07-20 00:00:00 | 0.66666 |
| 2016-08-05 00:00:00 | 0.33333 |
+---------------------+---------+

我不知道如何通过一个查询实现这一目标。当时,我是从这个查询开始的:

SELECT date_trunc('day',time) as "date", count(time) as errors
FROM log
WHERE status = '404 NOT FOUND'
GROUP BY date
ORDER BY errors DESC;

此查询结果:

+---------------------+--------+
| Date | Errors |
+---------------------+--------+
| 2016-07-20 00:00:00 | 2 |
| 2016-08-05 00:00:00 | 1 |
+---------------------+--------+

有什么想法或引用资料可以实现理想的结果吗?

最佳答案

要获得所需的输出,请尝试以下查询:

SELECT date_trunc('day',time) as "date", round((
count(*)::decimal/(
select count(*) from log WHERE status = '404 NOT FOUND')
),2) as errors
FROM log
WHERE status = '404 NOT FOUND'
GROUP BY date
ORDER BY errors DESC;

这将显示:

date                       errors
2016-07-20T00:00:00.000Z 0.67
2016-08-05T00:00:00.000Z 0.33

这是一个有效的 Fiddle

不用担心日期格式,在我的模式中我选择了timestamp 类型

关于从子查询计算百分比的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49195634/

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