PostgreSQL查询:如何按组汇总

时间:2018-09-18 21:55:19

标签: postgresql group-by

excel doc showing desired query output

数据: 有2种可能的状态,0或1 子状态和来源多种多样

我正在寻找创建一个查询来完成以下任务: 按周/年显示每个状态,子状态和源组合的唯一实例数。我确实有可以算作“实例数”的UID。

我写了以下内容:

SELECT date_part('week', date) as week, date_part('year', date) as year, active_date, status, sub_status, source, id
FROM public.users
WHERE status < 2
GROUP BY created_at, active_date, status, sub_status, source, id
ORDER BY created_at DESC

完成了以下任务: enter image description here

如何使它们汇总?

谢谢!

1 个答案:

答案 0 :(得分:0)

事实证明,术语“周”和“年”是保留字。通过将它们替换为“ theweek”和“ theyear”,并添加了count函数,我能够将它们汇总。

SELECT date_part('week', created_at) as theweek, date_part('year', created_at) as theyear, status, sub_status, source, Count(*)
FROM public.users
WHERE status < 2
GROUP BY theweek, theyear, status, sub_status, source
ORDER BY theweek DESC

结果如下:

results rolled up by week, year, status, sub-status, source

谢谢大家!