2016-10-11 167 views
0

在PostgreSQL 9.5數據庫中有一個表metrics_raw包含各種指標(類型:varchar)。 (例如):TRARTC
我執行下列SQL獲得年初至今每月彙總:PostgreSQL時間序列查詢與外部聯接

SELECT 
    count(*), 
    "ticks"."ts" AS "timestamp" 
FROM 
    "metrics_raw" 
RIGHT OUTER JOIN 
    generate_series('2016-01-01'::timestamp, '2016-10-10'::timestamp, '1 month'::interval) AS ticks(ts) 
ON 
    "ticks"."ts" = date_trunc('months', "metrics_raw"."timestamp") 
WHERE 
    "metrics_raw"."type" = 'TRA' OR 
    "metrics_raw"."type" IS NULL 
GROUP BY "ticks"."ts" 
ORDER BY "ticks"."ts" 

表包含TRA型(〜10條)和RTC類型的1條的一些記錄。
執行查詢的TRA我得到行的結果符合市場預期,但對RTC查詢我只得到行。還有一件事是沒有RTC指標我也得到行。

哪裏可能出錯?

+1

的問題是在哪裏的條件。您應該使用左外連接來轉換查詢,並將metric_raw.type =放入連接閉包中 – Nemeros

回答

0

謝謝@Nemeros,我固定的查詢是:

SELECT 
    "ticks"."ts" AS "timestamp" 
FROM 
    generate_series('2016-01-01'::timestamp, '2016-10-10'::timestamp, '1 month'::interval) AS ticks(ts) 
LEFT OUTER JOIN 
    (
    SELECT * 
    FROM "metrics_raw" 
    WHERE "metrics_raw"."type" = 'TRA' 
) as "metrics" 
ON 
    "ticks"."ts" = date_trunc('months', "metrics"."timestamp") 
GROUP BY "ticks"."ts" 
ORDER BY "ticks"."ts"