numerotate具有相同ID的行

时间:2017-11-08 10:56:08

标签: mysql

我有以下查询:

SELECT from_unixtime(table1.eventTime, '%Y %D %M') AS DAY, table1.ID, table1.eventTime, COUNT(*)
FROM table1 table1
GROUP BY from_unixtime(table1.eventTime, '%Y %D %M'), table1.ID, table1.eventTime

这给了我以下输出:

 DAY                    ID      eventTime COUNT(*)  
2017 10th November      815     1510275600  1  
2017 10th November      902     1510275600  1  
2017 10th November      1202    1510275600  1  
2017 10th November      1202    1510279200  1  
2017 10th November      1202    1510282800  1  
2017 10th November      1202    1510286400  1  
2017 10th November      1342    1510275600  1  
2017 10th November      1404    1510275600  1  
2017 10th November      1404    1510275600  1

我怎样才能做到这一点?

 DAY                 ID      eventTime COUNT(*)  
2017 10th November  815     1510275600  1  
2017 10th November  902     1510275600  1  
2017 10th November  1202    1510275600  1  
2017 10th November  1202    1510279200  2  
2017 10th November  1202    1510282800  3  
2017 10th November  1202    1510286400  4  
2017 10th November  1342    1510275600  1  
2017 10th November  1404    1510275600  1  
2017 10th November  1404    1510275600  2

实际上我需要的是按天分组并根据eventTime进行ID相同的编号。

1 个答案:

答案 0 :(得分:1)

你基本上是在mysql行号模拟之后。 SO中有大量的例子,这是另一个

drop table if exists t;
create table t
(Dt date, ID  int ,eventtime int);
insert into t values
('2017-11-10' ,815  ,1510275600), 
('2017-11-10' ,902  ,1510275600),
('2017-11-10' ,1202 ,1510275600),
('2017-11-10' ,1202 ,1510279200),
('2017-11-10' ,1202 ,1510282800),
('2017-11-10' ,1202 ,1510286400),
('2017-11-10' ,1342 ,1510275600),
('2017-11-10' ,1404 ,1510275600),
('2017-11-10' ,1404 ,1510275600);

select dt,id,eventtime,
         if(id <> @p,@rn:=1,@rn:=@rn+1) rownumber,
         @p:=id p
from t , (select @rn:=0,@p:=0) r
order  by id,dt,eventtime

结果

+------------+------+------------+-----------+------+
| dt         | id   | eventtime  | rownumber | p    |
+------------+------+------------+-----------+------+
| 2017-11-10 |  815 | 1510275600 |         1 |  815 |
| 2017-11-10 |  902 | 1510275600 |         1 |  902 |
| 2017-11-10 | 1202 | 1510275600 |         1 | 1202 |
| 2017-11-10 | 1202 | 1510279200 |         2 | 1202 |
| 2017-11-10 | 1202 | 1510282800 |         3 | 1202 |
| 2017-11-10 | 1202 | 1510286400 |         4 | 1202 |
| 2017-11-10 | 1342 | 1510275600 |         1 | 1342 |
| 2017-11-10 | 1404 | 1510275600 |         1 | 1404 |
| 2017-11-10 | 1404 | 1510275600 |         2 | 1404 |
+------------+------+------------+-----------+------+
9 rows in set (0.00 sec)