Sql 动态统计表中满足某些条件的前几行在表中某些列上的数量的方法

Sql 动态统计表中满足某些条件的前几行在表中某些列上的数量的方法,sql,db2,Sql,Db2,例如,我有一个表T,其中列customer和date表示个别客户购买的日期: customer | date ---------------------- A | 01/01/2013 A | 02/01/2013 A | 07/01/2013 A | 11/01/2013 B | 03/01/2013 B | 08/01/2013 我想为每对客户添加另一列,日期对c,d,给出T中

例如,我有一个表T,其中列customer和date表示个别客户购买的日期:

customer |   date   
----------------------  
       A | 01/01/2013 
       A | 02/01/2013
       A | 07/01/2013
       A | 11/01/2013
       B | 03/01/2013
       B | 08/01/2013       

我想为每对客户添加另一列,日期对c,d,给出T中对c',d'的数量,这样c=c'和0让我们从一些DDL开始。如果在问题中包含DDL和示例INSERT语句,您将得到更多的答案和更好的答案

create table test (
  customer char(1) not null,
  purchase_date date not null,
  primary key (customer, purchase_date)
);

insert into test values
('A', '2013-01-01'),
('A', '2013-01-02'),
('A', '2013-01-07'),
('A', '2013-01-11'),
('B', '2013-01-03'),
('B', '2013-01-10');
在标准SQL中,您可以使用以下内容。它不需要创建另一个表、外部联接或窗口函数。现在还不清楚您是否有充分的理由想要创建一个新表,但不需要获取正确的数据。我重命名了日期列以避免保留字

select t1.customer, t1.purchase_date, count(*) new_column
from test t1
inner join test t2 on t1.customer = t2.customer
and t2.purchase_date <= t1.purchase_date and t2.purchase_date > t1.purchase_date - interval '7 day'
group by t1.customer, t1.purchase_date
order by t1.customer, t1.purchase_date;

customer  purchase_date  new_column
--
A         2013-01-01     1
A         2013-01-02     2
A         2013-01-07     3
A         2013-01-11     2
B         2013-01-03     1
B         2013-01-10     1

这是否能够很好地扩展取决于DB2处理非equi连接的能力。我会指引你的。我希望purchase_date上的索引和限制性WHERE子句能够很好地执行。

您可以通过具有自联接的查询获得信息。为什么表中需要一个新列?
select t1.customer, t1.purchase_date, count(*) new_column
from test t1
inner join test t2 on t1.customer = t2.customer
and t2.purchase_date <= t1.purchase_date and t2.purchase_date > t1.purchase_date - interval '7 day'
group by t1.customer, t1.purchase_date
order by t1.customer, t1.purchase_date;

customer  purchase_date  new_column
--
A         2013-01-01     1
A         2013-01-02     2
A         2013-01-07     3
A         2013-01-11     2
B         2013-01-03     1
B         2013-01-10     1