具有外连接的 PostgreSQL 时间序列查询
PostgreSQL timeseries query with outer join
在 PostgreSQL 9.5 数据库中有一个 table metrics_raw 包含各种指标(类型:varchar).
类型是(例如):TRA、RTC.
我正在执行以下 SQL 以获得年初至今的月度汇总:
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"
table 包含一些 TRA 类型的记录(~10 条记录)和 1 个 RTC 类型的记录。
执行 TRA 的查询,我得到 10 行结果符合预期,但对于 RTC 查询,我只得到7 行。还有一件事是没有 RTC 指标我也得到 10 行。
哪里会出错?
感谢@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"
在 PostgreSQL 9.5 数据库中有一个 table metrics_raw 包含各种指标(类型:varchar).
类型是(例如):TRA、RTC.
我正在执行以下 SQL 以获得年初至今的月度汇总:
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"
table 包含一些 TRA 类型的记录(~10 条记录)和 1 个 RTC 类型的记录。
执行 TRA 的查询,我得到 10 行结果符合预期,但对于 RTC 查询,我只得到7 行。还有一件事是没有 RTC 指标我也得到 10 行。
哪里会出错?
感谢@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"