mysql - 仅选择符合条件的值
问题描述
我有以下(示例)表:
+----------+--------------+------------+------------+------------+
| 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 | |
+----------+--------------+------------+------------+------------+
目的是只选择活跃客户。假设和条件是:
- 一个 Customer_no 可以有多个订阅。
- 活跃客户 = 至少拥有一个活跃订阅的客户。
- 活动订阅是在以下情况下:状态 = 活动,start_date >= sysdate() 并且没有 end_date。
我将有很长的状态列表,可以使用 CASE 语句进行映射。是否知道如何根据该示例选择不同的活跃客户?我是一个初学者,不知道如何开始这项任务。
谢谢,帕维尔
解决方案
您对活跃客户的条件可以这样写:
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
。
推荐阅读
- excel - 如何在不使用工程函数的情况下将excel中的十进制转换为二进制
- python - 将存储为字符串的列表的 pandas 列拆分为多行(literal_eval 错误)
- android - 如何使浮动操作按钮变成椭圆形
- c# - WPF C# 和适当的体系结构
- git - 如何识别某个命名分支的分支点
- sql - 在一行中批量插入错误的数据
- azure-service-fabric - Service Fabric 中容器化服务的网络超时
- c# - 无法加载文件或程序集 PDFsharp
- loops - 循环错误:错误:无法分配大小为 1003.7 Mb 的向量
- sql - SQL Server:使用递归 CTE 查找与总数匹配的值的存储过程