【发布时间】:2015-06-16 22:56:26
【问题描述】:
所以我正在尝试将概览统计信息计算为 JSON,但无法将它们整理到查询中。
有2张桌子:
appointments
- time timestamp
- patients int
assignments
- user_id int
- appointment_id int
我想按用户、按小时计算当天的患者人数。理想情况下,它应该是这样的:
[
{hour: "2015-07-01T08:00:00.000Z", assignments: [
{user_id: 123, patients: 3},
{user_id: 456, patients: 10},
{user_id: 789, patients: 4},
]},
{hour: "2015-07-01T09:00:00.000Z", assignments: [
{user_id: 456, patients: 1},
{user_id: 789, patients: 6}
]},
{hour: "2015-07-01T10:00:00.000Z", assignments: []}
...
]
我有点接近了:
with assignments_totals as (
select user_id,sum(patients),date_trunc('hour',appointments.time) as hour
from assignments
inner join appointments on appointments.id = assignments.appointment_id
group by date_trunc('hour',sales.time),user_id
), hours as (
select to_char(date_trunc('hour',time),'YYYY-MM-DD"T"HH24:00:00.000Z') as hour, array_to_json(array_agg(DISTINCT assignment_totals)) as patients
from appointments
left join assignment_totals on date_trunc('hour',sales.time) = assignment_totals.hour
where time >= '2015-07-01T07:00:00.000Z' and time < '2015-07-02T07:00:00.000Z'
group by date_trunc('hour',time)
order by date_trunc('hour',time)
)
select array_to_json(array_agg(hours)) as hours from hours;
哪些输出:
[
{hour: "2015-07-01T08:00:00.000Z", assignments: [
{user_id: 123, patients: 3, hour: "2015-07-01T08:00:00.000Z" },
{user_id: 456, patients: 10, hour: "2015-07-01T08:00:00.000Z"},
{user_id: 789, patients: 4, hour: "2015-07-01T08:00:00.000Z"},
]},
{hour: "2015-07-01T09:00:00.000Z", assignments: [
{user_id: 456, patients: 1, hour: "2015-07-01T09:00:00.000Z"},
{user_id: 789, patients: 6, hour: "2015-07-01T09:00:00.000Z"}
]},
{hour: "2015-07-01T10:00:00.000Z", assignments: [null]}
...
]
虽然这可行,但有 2 个问题可能相互独立,也可能不相互独立:
- 如果该小时没有约会,我仍然希望将该小时包含在数组中(如示例中的上午 10 点),但要有一个空的“分配”数组。现在它在那里放了一个空值,我不知道如何在仍然保留时间的同时摆脱它。
- 我必须将小时与 user_id 和约会一起包含在分配条目中,因为我需要它将 assignments_totals 查询加入小时查询。但这是不必要的,因为它已经在父级中。
- 我觉得应该可以在 1 个 cte 和 1 个查询中完成,现在我使用的是 2 个 cte...但不知道如何压缩它并使其工作。
我想做类似的事情
hours as (
select to_char(date_trunc('hour',time),'YYYY-MM-DD"T"HH24:00:00.000Z') as hour, sum(appointments.patients) OVER(partition by assignments.user_id) as appointments
from appointments
left join assignments on appointments.id = assignments.appointment_id
where time >= '2015-07-01T07:00:00.000Z' and time < '2015-07-02T07:00:00.000Z'
group by date_trunc('hour',time)
order by date_trunc('hour',time)
)
select array_to_json(array_agg(hours)) as hours from hours
但如果不给我一个“属性必须在分组依据或聚合函数错误中”,我就无法让它工作。
有人知道如何解决这些问题吗?提前致谢!
【问题讨论】:
标签: json postgresql aggregate-functions common-table-expression