mysql 仅计算重叠的行

e5nqia27  于 2023-03-11  发布在  Mysql
关注(0)|答案(1)|浏览(111)

想要计算两个时间戳之间预订的设备的行数(* 将为COUNT(*)),它确实做到了这一点,但计数还包括拾取前返回的行。

SELECT * 
FROM `equipment` 
WHERE model_id = 1047 
  AND wh_return >= 1678084200 
  AND wh_pickup <= 1678688999

结果是这样的(非常简单),所以是2行而不是1行。

+--id--+-model_id-+-wh_pickup--|-wh_return--+
|27194 |   1047   | 1677652200 | 1678170599 |
|27378 |   1047   | 1678170600 | 1678861799 |

最好的方法是什么?我尝试了不同版本的EXISTS和JOIN,但是要么结果是2,要么什么都没有...
预期输出:我想知道在给定的时间内有多少个model_id被预订。在上面的例子中应该是一个;因为一个在下一个被拾取之前被返回。但是如果时间重叠,它应该是重叠的量

根据以下评论进行更新

源数据:

create table if not exists equipment
(
    id int auto_increment
        primary key,
    model_id int null,
    wh_pickup int null,
    wh_return int null
)

INSERT INTO equipment (id, model_id, wh_pickup, wh_return) VALUES 
(27121, 1047, 1677825000, 1677997799),
(27137, 1047, 1677997800, 1678084199),
(27194, 1047, 1677652200, 1678170599),
(27378, 1047, 1678170600, 1678861799),
(27388, 1047, 1678602600, 1678861799);

SQL:

SELECT COUNT(*) 
FROM `equipment` 
WHERE model_id = 1047 
  AND wh_return >= 1678084200 
  AND wh_pickup <= 1678688999

将输出3(ID:27194、27378和27388),但应输出2,因为ID 27194和27378未同时预订(一行在另一行被拾取之前返回)。其他行在时间戳窗口集之外,因此从查询中排除。

更新8.3添加了一些真实的数据和一些查询。为什么我得到的计数不同?DB Fiddle
由于解决方案在注解/dbfidle中很深,这就是我所需要的:

select MAX(cnt) 
FROM (
   select *,
      (select count(*) 
          from equipment e2 
          where e1.wh_pickup between e2.wh_pickup and e2.wh_return
          and e2.wh_return >= 1678689000 AND e2.wh_pickup <= 1678861799
          and e1.model_id = e2.model_id
          and e2.wh_return_ok = 0
          and e2.state NOT IN ('deleted', 'preprod')) as "cnt"
   from equipment e1
   where e1.wh_return >= 1678689000 AND wh_pickup <= 1678861799
   and e1.wh_return_ok = 0
   and e1.state NOT IN ('deleted', 'preprod')
   and e1.model_id = 1047) x;
kiayqfof

kiayqfof1#

仅计算没有重叠的行:

SELECT COUNT(*) 
FROM `equipment` e1
WHERE model_id = 1047 
  AND wh_return >= 1678084200 
  AND wh_pickup <= 1678688999
  and (select count(*) 
       from equipment e2 
       where e1.wh_pickup between e2.wh_pickup and e2.wh_return)=1

参见:DBFIDDLE
编辑:
“同时输出的项目(model_id)的最大数量”
我想你的意思是:

select MAX(cnt) 
FROM (
   select *,
      (select count(*) 
          from equipment e2 
          where e1.wh_pickup between e2.wh_pickup and e2.wh_return
          and e1.model_id = e2.model_id) as "cnt"
   from equipment e1
   where e1.wh_return >= 1678084200 AND wh_pickup <= 1678688999
   and e1.model_id = 1047) x

相关问题