首页 > 解决方案 > MySQL,获取行总和 = 3 的日期

问题描述

我想从约会列表中找到第三个可用的约会。

MySql 数据库的行以 RotaType、Date 和 UnusedSlots 作为列

我想做类似的事情

 $sql3 = "SELECT * FROM `UsageDailyUnusedSlots` WHERE Date >= '$Today' AND RotaType LIKE '%Derm%' AND UnusedSlots > 0 AND RotaType NOT LIKE '%- Y%' AND RotaType NOT LIKE '%- y%' ORDER BY Date LIMIT 1 OFFSET 2;";

但是,这会在第三天找到可用插槽,而不是第三天。

我可以对每一行做一个复杂的循环,将每次迭代/循环的值相加,并在总计 >= 3 时回显该值,但是我觉得必须有更好的方法。

这是一个场景

数据表

我上面的 sql 代码将选择 31/01/2020 作为 UnusedSlots 的第三天,但是我希望它选择 30/01/2020 作为日期,因为那是下一个未使用的第三个约会的日期

有什么想法吗?

谢谢

标签: sqlmariadb-10.3

解决方案


您可以使用 windows 功能找到您想要的插槽的具体位置。例如:

select *
from (
  select
    *,
    sum(`UnusedSlots`) over(order by Date 
      rows between unbounded preceding and 1 preceding) as previous_slots,
    sum(`UnusedSlots`) over(order by Date) as current_slots
  from `UsageDailyUnusedSlots`
  where Date >= '2020-01-15' 
    and RotaType like '%Derm%' 
    and RotaType not like '%- Y%' 
) x
where previous_slots < 3 and current_slots >= 3

推荐阅读