简体   繁体   中英

PostgreSQL timeseries query with outer join

In PostgreSQL 9.5 database there is a table metrics_raw containing various metrics ( types: varchar ).
Types are (for example): TRA , RTC .
I'm executing following SQL to get year-to-date monthly aggregations:

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"

The table contains some records of TRA type (~10 records) and 1 record of RTC type.
Executing the query for TRA I get 10 rows result as expected, but for RTC query I get only 7 rows. One more thing is that having no RTC metrics I get 10 rows too.

Where could be a mistake?

Thank @Nemeros, I fixed query to be:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM