gpt4 book ai didi

sql - 使用 CTE 对查询结果进行分组

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

我有一个基于 CTE 的查询,我向其中传递了大约 2600 个 4 元组纬度/经度值 - 这些值已被 ID 标记并保存在称为坐标的第二个表中。这些左上角和右下角的纬度/经度值被传递到 CTE,以显示在这些坐标内针对给定的两个时间戳发出的请求量(每小时)。

但是,我想在给定的时间戳内获取每天的总请求数。也就是说,我想获取每个指定日期的用户请求总数。例如。用户选择查看每周三或周三和周四等 - 在 2012 年 1 月 1 日至 16 日之间的 11:55 和 22:04 之间,我通过的每个纬度/经度 4 元组。输出基本上是这样的:

coordinates_id | stamp       | zcount

1 Jan 4 2012 200 (total requests on Wednesday Jan 4 between 11:55 and 22:04)
1 Jan 11 2012 121 (total requests on Wednesday Jan 11 between 11:55 and 22:04)
2 Jan 4 2012 255 (total requests on Wednesday Jan 4 between 11:55 and 22:04)
2 Jan 11 2012 211 (total requests on Wednesday Jan 11 between 11:55 and 22:04)
.
.
.

我该怎么做?我的查询如下:

WITH v AS (
SELECT '2012-01-1 11:55:11'::timestamp AS _from -- provide times once
,'2012-01-16 22:02:21'::timestamp AS _to
)
, q AS (
SELECT c.coordinates_id
, date_trunc('hour', t.calltime) AS stamp
, count(*) AS zcount
FROM v
JOIN mytable t ON t.calltime BETWEEN v._from AND v._to
AND (t.calltime::time >= v._from::time AND
t.calltime::time <= v._to::time) AND
(extract(DOW from t.calltime) = 3)
JOIN coordinates c ON (t.lat, t.lon)
BETWEEN (c.bottomrightlat, c.topleftlon)
AND (c.topleftlat, c.bottomrightlon)
GROUP BY c.coordinates_id, date_trunc('hour', t.calltime)
)
, cal AS (
SELECT generate_series('2011-2-2 00:00:00'::timestamp
, '2012-4-1 05:00:00'::timestamp
, '1 hour'::interval) AS stamp
FROM v
)
SELECT q.coordinates_id, cal.stamp, COALESCE (q.zcount, 0) AS zcount
FROM v, cal
LEFT JOIN q USING (stamp)
WHERE (extract(hour from cal.stamp) >= extract(hour from v._from) AND
extract(hour from cal.stamp) <= extract(hour from v._to)) AND
(extract(DOW from cal.stamp) = 3)
AND cal.stamp >= v._from AND cal.stamp <= v._to
GROUP BY q.coordinates_id, cal.stamp, q.zcount
ORDER BY q.coordinates_id ASC, stamp ASC;

它产生的样本结果是这样的:

coordinates_id  | stamp                | zcount
1 2012-01-04 16:00:00 1
1 2012-01-04 19:00:00 1
1 2012-01-11 14:00:00 1
1 2012-01-11 17:00:00 1
1 2012-01-11 19:00:00 1
2 2012-01-04 16:00:00 1

所以,正如我上面提到的,我希望将其视为

coordinates_id  | stamp      | zcount
1 2012-01-04 2
1 2012-01-11 3
2 2012-01-04 1

最佳答案

将您的最终 SELECT 更改为:

SELECT q.coordinates_id, cal.stamp::date, sum(q.zcount) AS zcount
FROM v, cal
LEFT JOIN q USING (stamp)
WHERE extract(hour from cal.stamp) BETWEEN extract(hour from v._from)
AND extract(hour from v._to)
AND extract(DOW from cal.stamp) = 3
AND cal.stamp >= v._from
AND cal.stamp <= v._to
GROUP BY 1,2
ORDER BY 1,2;

cal.stamp转换为日期的关键部分:cal.stamp::date
那,和 sum(q.zcount)

关于sql - 使用 CTE 对查询结果进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12737323/

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