将复杂逻辑转换为 MySQL CASE 语句

发布于 2024-10-24 13:21:54 字数 418 浏览 1 评论 0原文

我正在将以下逻辑转换为 MySQL CASE 语句,我确信有一种优雅的方法可以做到这一点,但我认为我已经工作太久了,让自己感到困惑!

业务规则:

  • 计划有一个programme_start和program_end
  • 个人有一个attend_start和attend_end

个人在一个时期内参加多个计划,他们只能有以下示例出勤范围之一:

在此处输入图像描述

我需要做的是将每个跨度分类为类别类型,即类型 1 ... 9。但是我在构建可以互斥的 CASE 语句时遇到了困难覆盖每个跨度。

以前有人做过这样的事情吗?如果没有,有人可以帮助解释其背后的逻辑吗?

提前致谢!

I'm having translating the following logic into a MySQL CASE statement, I'm sure there is an elegant way to do it but I think I have been working on for way too long and confused my self!

The business rules:

  • Programmes have an programme_start and programme_end
  • Individuals have an attend_start and attend_end

Individuals attend multiple programmes during one period, they can only have one of the following example attendance spans:

enter image description here

What I need to do is categorise each span into a category type i.e. Type 1 ... 9. but I'm having trouble building up a CASE statement that can mutually exclusively cover each span.

Has anyone done something like this before? If not could someone help with the logic behind it?

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青春如此纠结 2024-10-31 13:21:54

案例非常简单。

就单个时间而言,时间只能通过 3 种方式进行分类:之前、之中和之后。涉及两次,因此 3 x 3 = 9 个结果。

不过,关于一致性还有一些话要说,因为对于 _start 来说,它是:

on - after - before

而对于 _end 时间来说,它是

on - before - after

使用以下方式组合它们(假设不考虑 NULL):

case when programme_start = attend_start then 0
     when programme_start < attend_start then 3
     else 6 end
+
case when programme_end = attend_end then 1
     when programme_end > attend_end then 2
     else 3 end
AS Category

The cases are quite simple..

In the case of a single time, there are only 3 ways a time can be classified - before, on and after. There are two times involved, so 3 x 3 = 9 results.

There is something to be said about consistency though, because for _start, it goes:

on - after - before

Whereas for the _end time, it goes

on - before - after

Combine them using (assuming no consideration for NULLs):

case when programme_start = attend_start then 0
     when programme_start < attend_start then 3
     else 6 end
+
case when programme_end = attend_end then 1
     when programme_end > attend_end then 2
     else 3 end
AS Category
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文