我正在尝试获取一个结果集(并最终创建一个视图),该结果集将基于标识符合并行。以下是我所拥有的以及我要实现的目标的示例:
现有数据
/* +----+------+---------+------+-------------------+-------------------+ */ /* | 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 | */ /* +----+------+---------+------+-------------------+-------------------+ */
所需的输出:
/* +----+---------+-----+-------------------+ */ /* | ID | Name | Age | Address | */ /* +----+---------+-----+-------------------+ */ /* | 1 | Bob | 42 | 123 Muffin Lane | */ /* | 2 | Charles | 21 | 235 Sherbert Lane | */ /* +----+---------+-----+-------------------+ */
结果使用Entry_Create_Date确定最新记录。找到该行后,它将以此为基础。如果值为NULL,则使用具有相同ID值的其他行的值从中获取值。列值的优先级由其创建日期决定。
答案 0 :(得分:3)
这很复杂。您似乎想要每个字段的最新值。怎么样 。 。 。
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;
答案 1 :(得分:0)
您的样本数据建议我进行汇总(NOT EXACTLY
):
SELECT id, Name, MAX(Age), MAX(Address)
FROM table t
WHERE Age IS NOT NULL OR Address IS NOT NULL
GROUP BY id, Name;