我在 postgresql 9.2.4 中有一个复杂的(对我来说)SQL 查询,使用 generate_series 和多个连接。我需要汇总锻炼表中某一天所有锻炼的次数,并确保这些锻炼属于当前用户完成的锻炼。最后,我需要将该表加入一个系列以显示缺失的日期(使用 generate_series)。
我的想法是在 from 子句中选择系列,然后将系列加入到子查询中,该子查询具有练习和锻炼表之间的内部连接的结果。例如,我有以下查询:
SELECT
DISTINCT date_trunc('day', series.date)::date as date,
sum(COALESCE(reps, 0)) OVER WIN,
array_agg(workout_id) OVER WIN as ids
FROM (
select generate_series(-22, 0) + current_date as date
) series
LEFT JOIN (
exercises INNER JOIN workouts
ON exercises.workout_id = workouts.id
)
ON series.date = exercises.created_at::date
WINDOW
WIN AS (PARTITION BY date_trunc('day', series.date)::date)
ORDER BY date ASC;
这给出了以下输出:
date | sum | ids
------------+-----+---------------------------------------------------------
2013-04-27 | 0 | {NULL}
2013-04-28 | 432 | {49,48,47,46,45,44,43,42,41,38,37,36,36,36,36,35,34,33}
2013-04-29 | 0 | {NULL}
2013-04-30 | 20 | {50}
2013-05-01 | 0 | {NULL}
2013-05-02 | 0 | {NULL}
2013-05-03 | 0 | {NULL}
2013-05-04 | 0 | {NULL}
2013-05-05 | 0 | {NULL}
2013-05-06 | 0 | {NULL}
2013-05-07 | 40 | {51,51}
2013-05-08 | 0 | {NULL}
2013-05-09 | 0 | {NULL}
2013-05-10 | 0 | {NULL}
2013-05-11 | 0 | {NULL}
2013-05-12 | 0 | {NULL}
2013-05-13 | 0 | {NULL}
2013-05-14 | 0 | {NULL}
2013-05-15 | 0 | {NULL}
2013-05-16 | 20 | {52}
2013-05-17 | 0 | {NULL}
2013-05-18 | 0 | {NULL}
2013-05-19 | 0 | {NULL}
(23 rows)
但是,我想按某些条件过滤:
WHERE workouts.user_id = 5
例如。
但是,如果我将 WHERE 子句放入上面的查询中,输出是这样的:
date | sum | ids
------------+-----+---------------------------------------------------------
2013-04-28 | 432 | {49,48,47,46,45,44,43,42,41,38,37,36,36,36,36,35,34,33}
2013-04-30 | 20 | {50}
2013-05-07 | 40 | {51,51}
2013-05-16 | 20 | {52}
(4 rows)
该系列消失了。
如何按 user_id 过滤并保留系列?任何帮助将非常感激。