Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql 博士后连续累积计数_Postgresql_Sum_Cumulative Sum - Fatal编程技术网

Postgresql 博士后连续累积计数

Postgresql 博士后连续累积计数,postgresql,sum,cumulative-sum,Postgresql,Sum,Cumulative Sum,假设表a中有数据 | id | timestamp | |----|-------------| | 1 | 12345677677 | | 2 | 12345677677 | | 3 | 12346600000 | 我需要一个查询,返回给定时间点的累计计数 | timestamp | count| |-------------|------| | 12345677677 | 2 | | 12346600000 | 3 | 所以不是count()按

假设表a中有数据

| id | timestamp   |  
|----|-------------|
| 1  | 12345677677 |  
| 2  | 12345677677 |  
| 3  | 12346600000 | 
我需要一个查询,返回给定时间点的累计计数

| timestamp   | count| 
|-------------|------|
| 12345677677 | 2    | 
| 12346600000 | 3    |
所以不是count()按时间戳分组,而是count()按时间戳分组+以前的计数

多亏了@klin,这一切都很完美;但是,使用window函数时,我在一次查询中获取每天的不同计数(*)和累计总和时遇到了一个问题

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()
作为带有
orderby
子句的窗口函数。Postgres中有一个很好的功能,
上进行区分以消除重复行:

select distinct on(timestamp) timestamp, count(*) over (order by timestamp)
from my_table;

  timestamp  | count 
-------------+-------
 12345677677 |     2
 12346600000 |     3
(2 rows)    
使用
count()
作为带有
orderby
子句的窗口函数。Postgres中有一个很好的功能,
上进行区分以消除重复行:

select distinct on(timestamp) timestamp, count(*) over (order by timestamp)
from my_table;

  timestamp  | count 
-------------+-------
 12345677677 |     2
 12346600000 |     3
(2 rows)    

谢谢,但是现在我得到了带有count和sum的笛卡尔积,请参见我编辑的问题:)@user39950:当然,您得到了笛卡尔积,因为您没有加入
addon_user
表和您的派生表(子查询)@user39950-当您在FROM子句中使用两个表而不使用联接条件时,您总是得到笛卡尔乘积。我不清楚为什么要将查询放在FROM子句中,以及列
sum
来自何处。也许你应该问一个新问题,包括完整的示例输入数据和预期结果。谢谢,但现在我得到了带有计数和求和的笛卡尔积,请参阅我编辑的问题:)@user39950:当然你得到了笛卡尔积,因为你没有加入
addon\u user
表和派生表(子查询)@user39950-当您在FROM子句中使用两个表而不使用联接条件时,您总是得到笛卡尔乘积。我不清楚为什么要将查询放在FROM子句中,以及列
sum
来自何处。也许你应该问一个新问题,包括完整的示例输入数据和预期结果。