sql - 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 作为日期,因为那是下一个未使用的第三个约会的日期
有什么想法吗?
谢谢
解决方案
您可以使用 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
推荐阅读
- c# - 在配置文件中使用带有 connectionString 的 ObjectContext 并动态加载密码
- java - 从会员应用程序发出会员请求时出错
- c# - 为什么 ReadOnlySpan 不能用作泛型委托和泛型方法的类型参数?
- python - PostgreSql/SQLalchemy 创建包含错误数据类型的列的表
- xaml - 显示与 Xamarin.Forms Previewer 不同的输出的模拟器
- python - 如何让python自动发送邮件
- mysql - mysql比较2个子字符串列
- angular - 在非 Angular 类中获取注入的依赖项
- python - Python3 Cryptodome - 如何解密 pem?
- python - 在虚拟环境中安装 python 站点包