gpt4 book ai didi

postgresql - 在 postgres/COALESCE 中正确使用 COALESCE 无法正常工作

转载 作者:行者123 更新时间:2023-11-29 12:37:37 26 4
gpt4 key购买 nike

我正在尝试返回有关所执行搜索次数的每小时报告。我的结果不包括搜索为零的时间,我认为我的语法正确,可以使用 COALESCE。谁能看到我做错了什么?谢谢

SELECT CAST(startdatetime as Date),extract(hour from startdatetime) as hr, COALESCE(count(distinct id),0) as average_per_hour
FROM search WHERE CAST(startdatetime As Date) = '2014/07/05'
GROUP BY CAST(startdatetime as Date),extract(hour from startdatetime)
ORDER BY CAST(startdatetime as Date),extract(hour from startdatetime)

enter image description here

最佳答案

一些改进,但与@a_horse_with_no_name 的回答基本相同:

SELECT DATE '2014-07-05', hr, COUNT(DISTINCT id) AS average_per_hour
FROM generate_series(0, 23) hr
LEFT JOIN search ON EXTRACT(HOUR FROM startdatetime) = hr AND CAST(startdatetime AS DATE) = '2014-07-05'
GROUP BY hr
ORDER BY hr

ORDER BYGROUP BY 中使用 CAST(startdatetime AS DATE) 是无关紧要的,因为您只搜索一天。如果通常情况并非如此,您还需要调整 generate_series()

编辑:

这适用于多天:

SELECT CAST(hr AS DATE), EXTRACT(HOUR FROM hr), COUNT(DISTINCT id) AS average_per_hour
FROM generate_series('2014-07-05 00:00:00', '2014-07-06 23:00:00', INTERVAL '1' HOUR) hr
LEFT JOIN search ON date_trunc('hour', startdatetime) = hr
GROUP BY hr
ORDER BY hr

关于postgresql - 在 postgres/COALESCE 中正确使用 COALESCE 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24651109/

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