sql - SQL 将多行合二为一
问题描述
我想将多行合并为一行,并且只保留值不为 NULL 的值
这是我想要实现的目标:
我想从这个
+----+-----------------+-----------------+-----------------+--------------------+
| ID | 1stNofification | 2ndNotification | 3rdNotification | NotificationNumber |
+----+-----------------+-----------------+-----------------+--------------------+
| 1 | 01.01.2019 | NULL | NULL | 1 |
+----+-----------------+-----------------+-----------------+--------------------+
| 1 | NULL | 02.02.2019 | NULL | 2 |
+----+-----------------+-----------------+-----------------+--------------------+
| 1 | NULL | NULL | 03.03.2019 | 3 |
+----+-----------------+-----------------+-----------------+--------------------+
| 2 | 06.01.2019 | NULL | NULL | 1 |
+----+-----------------+-----------------+-----------------+--------------------+
| 2 | NULL | 09.02.2019 | NULL | 2 |
+----+-----------------+-----------------+-----------------+--------------------+
| 2 | NULL | NULL | 11.03.2019 | 3 |
+----+-----------------+-----------------+-----------------+--------------------+
对此:
+----+-----------------+-----------------+-----------------+
| ID | 1stNofification | 2ndNotification | 3rdNotification |
+----+-----------------+-----------------+-----------------+
| 1 | 01.01.2019 | 02.02.2019 | 03.03.2019 |
+----+-----------------+-----------------+-----------------+
| 2 | 06.01.2019 | 09.02.2019 | 11.03.2019 |
+----+-----------------+-----------------+-----------------+
我试过类似的东西:
SELECT
ID,
MAX(CASE WHEN a.NotificationNumber = 1 THEN 1stNotification END)1stNotification,
MAX(CASE WHEN a.NotificationNumber = 2 THEN 2ndNotification END)2ndNotification,
MAX(CASE WHEN a.NotificationNumber = 3 THEN 3rdNotification END)3rdNotification
FROM Notifications
GROUP BY ID
但不幸的是,这并没有给我预期的结果。
如果有人可以帮助我,我将不胜感激:)
解决方案
你只需要使用 max 没有任何情况
SELECT
ID,
MAX(1stNotification) AS 1stNotification,
MAX(2ndNotification) AS 2ndNotification,
MAX(3rdNotification) AS 3rdNotification
FROM Notifications
GROUP BY ID
推荐阅读
- arrays - Rails:fields_for 迭代编辑表单的列表项
- next.js - 将 NextJS 部署到 Vercel 失败
- python - 在 scipy.differential_evolution 中执行workers参数时出错
- gradle - Intellij Idea:即使从命令行成功,Gradle 同步也会取消
- amazon-web-services - AWS 新手。我需要为 kinesis 分析应用程序创建一个云形成模板。输入是运动数据流,输出是 lambda 函数
- plsql - 如何在 oracle plsql 中产生 kafka 事件
- java - 重定向到 java web-app 后无法获取 AuthenticationResult
- javascript - chorme 扩展 - 如何替换用户选择的文本
- python - 如何使用 List Comprehension 和 Pydash 按键查找特定 JSON 值
- python - 捕获拼写错误的 Python 对象属性的简单方法?