2
我有一個基於CTE的查詢,其中我傳遞了大約2600個4元組緯度/經度值 - 這些值已被標記並保存在稱爲座標的第二個表中。將這些左上角和右下角經度/緯度值傳遞給CTE,以顯示給定兩個時間戳的請求數量(小時)。用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
我剛剛看到一篇文章,您稱PostgreSQL的「Good Guy Greg」。我同意那個。 – sm90901
@ sm90901:恩,謝謝。 :) –
剛剛注意到一個小問題 - 實際上我忘了首先問這個問題 - 在我的「初始」版本中 - 當我只需要總查詢數和其他任何類似lat/lons-時,我的查詢還打印了具有0計數的行感謝'COALESCE(q.zcount,0)'。我如何將它應用到這種情況,以獲得zcount 0的行?我將'COALESCE'應用於'sum(q.zcount)',但沒有按照我的計劃工作。 – sm90901