[英]Postgres continuous cumulative count
假設表a有數據
| id | timestamp |
|----|-------------|
| 1 | 12345677677 |
| 2 | 12345677677 |
| 3 | 12346600000 |
我查詢一個查詢,該查詢返回給定時間點的累計計數
| timestamp | count|
|-------------|------|
| 12345677677 | 2 |
| 12346600000 | 3 |
因此,不是按時間戳記的count( )組,而是按時間戳記+先前的計數來划分count( )。
感謝@klin,它可以完美地工作; 但是,使用窗口函數時,我每天在一個查詢中獲取不重復count(*)以及累積總和時遇到問題。
SELECT date_trunc('day', date_created) AS date,
sum,
count(*)
FROM addon_user,
(SELECT DISTINCT ON(date_trunc('day', date_created))
date_trunc('day', date_created),
count(*)
OVER (
ORDER BY date_trunc('day', date_created)) AS sum
FROM addon_user
) AS sub
GROUP BY date,
sum
ORDER BY date ASC
返回笛卡爾積:
timestamp | count |sum
-------------+-------+---
12345677677 | 2|2
12345677677 | 2|5
12346600000 | 3|2
12346600000 | 3|5
而我需要以下形式的數據
timestamp | count |sum
-------------+-------+---
12345677677 | 2|2
12346600000 | 3|5
使用count()
作為帶有order by
子句的窗口函數。 有一個很好的功能Postgres里, distinct on
消除重復行:
select distinct on(timestamp) timestamp, count(*) over (order by timestamp)
from my_table;
timestamp | count
-------------+-------
12345677677 | 2
12346600000 | 3
(2 rows)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.