首页 > 解决方案 > 仅选择符合条件的值

问题描述

我有以下(示例)表:

+----------+--------------+------------+------------+------------+
| Customer | Subscription | Status     | Start Date | End Date   |
+----------+--------------+------------+------------+------------+
|       1  | 1a001        | Pending    | 02.02.2020 |            |
|       1  | 1b002        | Pending    | 02.02.2020 | 05.02.2020 |
|       1  | 1c003        | Rejected   | 02.02.2020 |            |
|       1  | 1d004        | Incomplete | 02.02.2020 |            |
|       1  | 1e005        | Pending    | 07.02.2020 |            |
|       1  | 1f006        | Active     | 07.02.2020 |            |
|       2  | 2a001        | Pending    | 02.02.2020 |            |
|       2  | 2b002        | Pending    | 02.02.2020 |            |
|       2  | 3c003        | Rejected   | 02.02.2020 |            |
|       2  | 4d004        | Incomplete | 02.02.2020 |            |
|       2  | 5e005        | Pending    | 07.02.2020 | 07.02.2020 |
|       2  | 6f006        | Active     | 07.02.2020 |            |
+----------+--------------+------------+------------+------------+

目的是只选择活跃客户。假设和条件是:

  1. 一个 Customer_no 可以有多个订阅。
  2. 活跃客户 = 至少拥有一个活跃订阅的客户。
  3. 活动订阅是在以下情况下:状态 = 活动,start_date >= sysdate() 并且没有 end_date。

我将有很长的状态列表,可以使用 CASE 语句进行映射。是否知道如何根据该示例选择不同的活跃客户?我是一个初学者,不知道如何开始这项任务。

谢谢,帕维尔

标签: mysqlbusiness-intelligence

解决方案


您对活跃客户的条件可以这样写:

status = 'Active' and start_date >= curdate() and end_date is null

所以group by customer并使用having子句中的条件:

select customer
from tablename
group by customer
having sum(status = 'Active' and start_date >= curdate() and end_date is null)

如果sum()返回0,则将其评估为false
在任何其他情况下,它被评估为true


推荐阅读