我正在尝试创建一个参数查询,该查询将使用 plpgsql 在循环中执行。
2 个参数将是传入查询的起始纬度/经度点。纬度和经度点将从数组中检索 - 因此它将是对数组的类似 foreach 的迭代,并将两个纬度/经度值传递给每次执行的查询。
我该怎么做这样的事情?
我的查询和我认为的实现方式如下:(X、Z 值是将传递的参数纬度/经度值,Y 和 T 将通过执行我将处理的特定计算获得)。为清楚起见,我的查询返回多行和多列结果(时间戳和计数),因为它计算并返回属于小时间隔的请求数(时间戳)
for each latitude-longitude pair X,Z in array
find Y and T from X and Z
WITH cal AS (
SELECT generate_series('2011-02-02 00:00:00'::timestamp ,
'2012-04-01 05:00:00'::timestamp ,
'1 hour'::interval) AS stamp
),
qqq AS (
SELECT date_trunc('hour', calltime) AS stamp, count(*) AS zcount
FROM mytable
WHERE calltime >= '2011-02-13 22:55:11'
AND calltime <= '2012-02-13 01:02:21'
AND (calltime::time >= '22:55:11'
OR calltime::time <= '01:02:21')
AND lat >= X
AND lat <= Y
AND lon >= Z
AND lon <= T
GROUP BY date_trunc('hour', calltime)
)
SELECT cal.stamp, COALESCE (qqq.zcount, 0) AS zcount
FROM cal
LEFT JOIN qqq ON cal.stamp = qqq.stamp
WHERE cal.stamp >= '2011-02-13 22:00:00'
AND cal.stamp <= '2012-02-13 01:02:21'
AND (
extract ('hour' from cal.stamp) >= extract ('hour' from '2011-02-13 22:00:00'::timestamp) or
extract ('hour' from cal.stamp) <= extract ('hour' from '2012-02-13 01:02:21'::timestamp)
)
ORDER BY stamp ASC;