我有Users
表。每行都有字段(列)createdAt
(类型为timestamp with time zone
),表示用户何时创建。我必须显示简单的折线图,它将在给定时间段(minDate,maxDate)中显示及时(每天,每周或每年)的用户数量。我知道怎么分组和例如按年份对用户进行计数,但每次计数将是今年创建的用户数量,我想要的是从开始到此日期创建的用户数量。我怎么能在postgres中做到这一点?
这是一个代码,它只返回每天创建的用户数:
SELECT COUNT(*) AS "total", date_trunc('day',u."createdAt") as "day"
FROM "Users" u
GROUP BY "day"
ORDER BY "day"
我需要的是第二行。总计为199
,第三行204
,依此类推。因此,每行总计是row.toal
+之前所有rows.total
的总和。
答案 0 :(得分:1)
我更喜欢使用窗口函数而不是重新查询数据。
SELECT COUNT(*) AS "dailyCount", date_trunc('day',u."createdAt") as "day",
sum(count(*)) over( order by date_trunc('day',u."createdAt"))
FROM "Users" u
GROUP BY "day"
ORDER BY "day"
答案 1 :(得分:0)
我找到了答案:
SELECT day, "dailyCount", "dailyCount" + (SELECT COUNT(*) FROM "Users" u2 WHERE date_trunc('day',u2."createdAt") < day) as "totalCount"
FROM (
SELECT COUNT(*) AS "dailyCount", date_trunc('day',u."createdAt") as "day"
FROM "Users" u
GROUP BY "day"
ORDER BY "day"
) daily