SQL Server中按ID合并多行数据为单行的技术求助
问题:SQL Server 按ID聚合并填充有效字段值
原始数据集:
| ID | CoinWeightWarning | NoteCountWarning | NoteValueWarning |
|---|---|---|---|
| 165 | NULL | NULL | NULL |
| 165 | NULL | NULL | NULL |
| 165 | NULL | 2000 | NULL |
| 165 | NULL | NULL | 75000 |
| 166 | NULL | NULL | 75000 |
| 166 | 10 | NULL | NULL |
| 166 | NULL | 2000 | NULL |
需要转换为以下结果集:
| ID | CoinWeightWarning | NoteCountWarning | NoteValueWarning |
|---|---|---|---|
| 165 | NULL | 2000 | 75000 |
| 166 | 10 | 2000 | 75000 |
测试表INSERT语句:
DECLARE @Test TABLE (Id int, CoinWeightWarning int, NoteCountWarning int, NoteValueWarning int) INSERT INTO @Test VALUES (165, NULL, NULL, NULL) ,(165, NULL, NULL, NULL) ,(165, NULL, 2000, NULL) ,(165, NULL, NULL, 75000) ,(166, NULL, NULL, NULL) ,(166, NULL, NULL, NULL) ,(166, 10, NULL, NULL) ,(166, NULL, NULL, NULL) ,(166, NULL, 2000, NULL) ,(166, NULL, NULL, 75000)
解决方案
使用聚合函数MAX()按ID分组,该函数会自动忽略NULL值,提取每个ID下对应字段的有效非空值;同时通过HAVING子句排除所有字段均为NULL的ID行:
SELECT Id, MAX(CoinWeightWarning) AS CoinWeightWarning, MAX(NoteCountWarning) AS NoteCountWarning, MAX(NoteValueWarning) AS NoteValueWarning FROM @Test GROUP BY Id HAVING MAX(CoinWeightWarning) IS NOT NULL OR MAX(NoteCountWarning) IS NOT NULL OR MAX(NoteValueWarning) IS NOT NULL
说明
MAX()函数会忽略NULL,返回分组内对应字段的非空值(若业务中每个ID对应字段仅存在一个有效非空值,此方法完全适用;若存在多个非空值,会返回最大值)HAVING子句用于过滤掉所有字段都为NULL的ID行,满足“无需保留仅含NULL值的行”的要求
内容的提问来源于stack exchange,提问作者BummzuaBua
相关产品推荐
相关产品推荐

