计算a之间b的个数

eyh26e7m  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(326)

我在计算数据库中每个a之前我得到了多少个b。
类似表格:

ID  -  value  -  datetime
10       A     2018-10-10 10:10:10
 9       B     2018-10-10 09:09:09
 8       B     2018-10-10 08:08:08
 7       B     2018-10-10 07:07:07
 6       B     2018-10-10 06:06:06
 5       A     2018-10-10 05:05:05
 4       B     2018-10-10 04:04:04
 3       B     2018-10-10 03:03:03
 2       B     2018-10-10 02:02:02
 1       A     2018-10-10 01:01:01

但我想从

ID  -         datetime   -    count 
10    2018-10-10 10:10:10      4
 5    2018-10-10 05:05:05      3
 1    2018-10-10 01:01:01      0

类似于:计算行与行之间的行数
编辑:
在答案的帮助下,我把它修改成了我自己的表格

SELECT a.ID
     , COALESCE(b.i,0) cnt
  FROM 
     ( SELECT x.*
            , MAX(y.ID) y_ID
         FROM tapdatabeer x         
         LEFT
         JOIN tapdatabeer y
           ON y.ID < x.ID
          AND y.beerstatus = '0'
        WHERE x.beerstatus = '1' AND x.beerline = 5 AND x.masterID = 4015
        GROUP 
           BY x.ID
     ) a
  LEFT
  JOIN 
     ( SELECT ID
            , beerstatus            
            , CASE WHEN beerstatus = '0' then @i:=@i+1 ELSE @i:=0 END i 
         FROM tapdatabeer 
            , (SELECT @i:=0) vars 
        WHERE beerline = 5 AND masterID = 4015 
        ORDER 
           BY ID
     ) b
    ON b.ID = a.y_ID

我已经手动检查了这里每行的结果应该在200到210之间。我得到这个的原因是因为我的id不在一行,因为这个表中还有c和d。我需要为查询创建一个自定义计数器。但我的结果是:

ID    cnt
258991    0
265187    0
266442    0
272383    0
273134  206
277077    0
5n0oy7gb

5n0oy7gb1#

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,value CHAR(1) NOT NULL
);

INSERT INTO my_table VALUES
('A'),('B'),('B'),('B'),('A'),('B'),('B'),('B'),('B'),('A');

SELECT a.id
     , COALESCE(b.i,0) cnt
  FROM 
     ( SELECT x.*
            , MAX(y.id) y_id
         FROM my_table x
         LEFT
         JOIN my_table y
           ON y.id < x.id
          AND y.value = 'b'
        WHERE x.value = 'a'
        GROUP 
           BY x.id
     ) a
  LEFT
  JOIN 
     ( SELECT id
            , value
            , CASE WHEN value = 'b' then @i:=@i+1 ELSE @i:=0 END i 
         FROM my_table 
            , (SELECT @i:=0) vars 
        ORDER 
           BY id
     ) b
    ON b.id = a.y_id;

+----+------+
| id | cnt  |
+----+------+
|  1 |    0 |
|  5 |    3 |
| 10 |    4 |
+----+------+

相关问题