sql - Flattening mutliple Rows into a single row based on identifier
问题描述
I'm trying to get a result set (and eventually create a view) that will combine rows based on an identifier. Below is an example of what I have, and what I'm trying to achieve:
Existing Data
/* +----+------+---------+------+-------------------+-------------------+ */ /* | ID | GUID | Name | Age | Address | Entry_Create_Date | */ /* +----+------+---------+------+-------------------+-------------------+ */ /* | 1 | 123 | Bob | 42 | NULL | 1/2/2018 | */ /* | 1 | 245 | Bob | 41 | 123 Muffin Lane | 1/1/2018 | */ /* | 1 | 356 | Bob | NULL | NULL | 1/3/2018 | */ /* | 2 | 456 | Charles | 21 | 235 Sherbert Lane | 1/3/2018 | */ /* +----+------+---------+------+-------------------+-------------------+ */
Desired output:
/* +----+---------+-----+-------------------+ */ /* | ID | Name | Age | Address | */ /* +----+---------+-----+-------------------+ */ /* | 1 | Bob | 42 | 123 Muffin Lane | */ /* | 2 | Charles | 21 | 235 Sherbert Lane | */ /* +----+---------+-----+-------------------+ */
Results use the Entry_Create_Date to determine the latest record. Once that row is found, it uses that as the basis. If the values are NULL, it uses the values of the other rows with the same ID value to get the values from them. Precedence of column value is determined by the date it was created.
解决方案
This is complicated. You seem to want the most recent value from each field. How about . . .
select distinct id, name,
first_value(age) over (partition by id order by case when age is not null then 1 else 2 end, Entry_Create_Date desc) as age,
first_value(Address) over (partition by id order by case when Address is not null then 1 else 2 end, Entry_Create_Date desc) as Address
from t;
推荐阅读
- php - ContactForm7 在提交 WordPress Woocommerce 网站时显示 POST 和 GET 错误
- c# - 如何获取所有显示器联合中的矩形,该区域不包含在显示器区域中
- jquery - 如何为 jQuery 数据表 AJAX 调用编写 Jasmine 单元测试?
- javascript - 使用 cookie 在页面之间交换数据
- c - strstr 没有返回想要的结果
- google-chrome - 如何获取 chrome 扩展的存档?
- javascript - 如何使用 axios 和 useEffect 过滤 JSON 数据?
- javascript - 段落等中使用的 HTML 变量
- c - C、字符串实习生池和DLL?
- python - 将 GitlabCI 中的文件变量传递给 Docker 运行 (FileNotFound)