PostgreSQL:按日期分组,包括前几天';结果也是如此

PostgreSQL:按日期分组,包括前几天';结果也是如此,sql,postgresql,Sql,Postgresql,对不起,如果这变成了一个双重职位 我正在写一个查询,确定持有某个基金股份的客户数量,按该基金每天发生的交易分组 因此,我的事务表是: CREATE TABLE trans( transID SERIAL PRIMARY KEY, sin CHAR(9) REFERENCES customer(sin) ON UPDATE CASCADE ON DELETE CASCADE, fundID INT REFERENCES fund(fundID) NOT NULL, transDate DATE,

对不起,如果这变成了一个双重职位

我正在写一个查询,确定持有某个基金股份的客户数量,按该基金每天发生的交易分组

因此,我的事务表是:

CREATE TABLE trans(
transID SERIAL PRIMARY KEY,
sin CHAR(9) REFERENCES customer(sin) ON UPDATE CASCADE ON DELETE CASCADE,
fundID INT REFERENCES fund(fundID) NOT NULL,
transDate DATE,
shares INT,
FOREIGN KEY (fundID) REFERENCES fund(fundID) ON UPDATE CASCADE ON DELETE CASCADE
);
我的问题是:

   select f.transdate, count (f.sin) 
   from (select t1.transdate, t1.sin, sum(t2.shares) 
          from fund f natural join trans t1 natural join trans t2 
          where f.fundname='Energy' 
          and t1.sin = t2.sin 
          and t2.transdate <= t1.transdate 
          group by t1.transdate, t1.sin 
          having sum(t2.shares) > 0)as f group by f.transdate 
          order by f.transdate;
因此,我所说的查询将返回以下结果:

 transdate  | count 
------------+-------
 2011-10-10 |     1
 2011-10-11 |     1
 2011-10-17 |     2
然而,我希望它是这样的:

 transdate  | count 
------------+-------
 2011-10-10 |     1
 2011-10-11 |     2
 2011-10-17 |     4
如你所见,在2011-10-11年末,共有2人持有该基金的股份,以此类推


有什么帮助吗?

您需要的是一个窗口功能,特别是使用“滞后”功能。我不确定您的PostgreSQL是什么版本,以及这些窗口功能是何时首次得到支持的,但以下是当前9.x系列的文档:

窗口化概述:

以及:

窗口功能:

考虑到这一点,可能有一种相当有效的方法来重写您的查询,但我没有时间来处理这个问题。我可以说,获得预期结果的最简单(即使不是最好的)方法是接受当前查询,将其设置为CTE(),并在使用CTE的查询中使用windowing函数。意思是:

WITH cte (transdate, peoplecount) AS (
 your_current_query
)
SELECT transdate, lag() OVER (...)
FROM cte;
类似的东西。希望这有帮助:)

WITH cte (transdate, peoplecount) AS (
 your_current_query
)
SELECT transdate, lag() OVER (...)
FROM cte;