对之前未计算的列的值和计数值进行分组和计数

时间:2015-08-27 06:35:05

标签: mysql

我使用MySQL,因为我有一个这样的表。

id  | p_no    | date
1   | 100001  | 2015-01-01
2   | 100002  | 2015-01-01
3   | 100003  | 2015-01-01
4   | 100004  | 2015-01-01
5   | 100003  | 2015-01-02
6   | 100004  | 2015-01-02
7   | 100005  | 2015-01-02
8   | 100004  | 2015-01-03
9   | 100003  | 2015-01-03
10  | 100002  | 2015-01-03
11  | 100001  | 2015-01-03
12  | 100005  | 2015-01-04
13  | 100006  | 2015-01-04
14  | 100007  | 2015-01-04
15  | 100008  | 2015-01-04

从该表中我想得到p_no 按日期分组的新计数。我希望结果如下。

date       | count
2015-01-01 | 4
2015-01-02 | 1
2015-01-03 | 0
2015-01-04 | 3

我想像下面这样计算。

id  | p_no    | date
1   | 100001  | 2015-01-01
2   | 100002  | 2015-01-01
3   | 100003  | 2015-01-01
4   | 100004  | 2015-01-01   -- new count 4
-----------------------------------------------
5   | 100003  | 2015-01-02
6   | 100004  | 2015-01-02
7   | 100005  | 2015-01-02   -- new count 1 (p_no 100003 & 100004 are already counted on the previous day)
-----------------------------------------------
8   | 100004  | 2015-01-03
9   | 100003  | 2015-01-03
10  | 100002  | 2015-01-03
11  | 100001  | 2015-01-03   -- new count 0 (because all the p_no are counted before)
-----------------------------------------------
12  | 100005  | 2015-01-04
13  | 100006  | 2015-01-04
14  | 100007  | 2015-01-04
15  | 100008  | 2015-01-04   -- new count 3 (p_no 100005 is counted before)

我必须通过查询本身执行此操作,而不使用任何外部脚本。所以,请指导我。

1 个答案:

答案 0 :(得分:1)

create table thing1
(   id int auto_increment primary key,
    p_no int not null,
    theDate date not null
);
insert thing1 (p_no,theDate) values
(100001,'2015-01-01'),
(100002,'2015-01-01'),
(100003,'2015-01-01'),
(100004,'2015-01-01'),
(100003,'2015-01-02'),
(100004,'2015-01-02'),
(100005,'2015-01-02'),
(100004,'2015-01-03'),
(100003,'2015-01-03'),
(100002,'2015-01-03'),
(100001,'2015-01-03'),
(100005,'2015-01-04'),
(100006,'2015-01-04'),
(100007,'2015-01-04'),
(100008,'2015-01-04');

查询:

select theDate,sum(blahblah) as theCount
from
(   select t.theDate,x.p_no,
    case when x.p_no is null then 0 else 1 end as blahblah
    from thing1 t
    left join
    (  select p_no,min(theDate) as xDate
       from thing1
       group by p_no
    ) x
    on x.p_no=t.p_no and t.theDate<=x.xDate
) y
group by theDate
order by theDate
+------------+----------+
| theDate    | theCount |
+------------+----------+
| 2015-01-01 |        4 |
| 2015-01-02 |        1 |
| 2015-01-03 |        0 |
| 2015-01-04 |        3 |
+------------+----------+