使用此数据集:
| RECID | ID | VALUE1 | VALUE2 | VALUE3 | RECDT |
----------------------------------------------------------------------------
| 1 | 1-01 | 1 | 2 | 3 | January, 01 2013 00:00:00+0000 |
| 2 | 1-01 | 3 | (null) | (null) | January, 02 2013 00:00:00+0000 |
| 3 | 1-01 | (null) | (null) | 1 | January, 03 2013 00:00:00+0000 |
是否可以通过简单的查询返回以下结果?
| ID | VALUE1 | VALUE2 | VALUE3 |
-----------------------------------
| 1-01 | 3 | 2 | 1 |
数据集需要根据日期和 PtID 返回每列的最新值。因此,举例来说,如果我对 2013 年 1 月 2 日之前 PTID 的所有更改感兴趣,结果将如下所示:
| ID | VALUE1 | VALUE2 | VALUE3 |
-----------------------------------
| 1-01 | 3 | 2 | 3 |
架构已于 sqlfiddle 启动对于任何有兴趣的人。
最佳答案
下面是一种适用于多种 SQL 方言的方法:
select ptid,
(select value1 from t t2 where t2.ptid = t.ptid and value1 is not null order by recdt desc limit 1
) as Value1,
(select value2 from t t2 where t2.ptid = t.ptid and value2 is not null order by recdt desc limit 1
) as Value2,
(select value3 from t t2 where t2.ptid = t.ptid and value3 is not null order by recdt desc limit 1
) as Value3
from t
where ptid = '1-01'
group by ptid
某些数据库可能更喜欢 top
或 recnum = 1
而不是 limit
。
在MySQL中,你还可以这样做:
select ptid,
substring_index(group_concat(value1 order by recdt desc), ',', 1) as Value1,
substring_index(group_concat(value2 order by recdt desc), ',', 1) as Value2,
substring_index(group_concat(value3 order by recdt desc), ',', 1) as Value3
from t
group by ptid
这会产生将值转换为字符串的副作用。您可以转换回您想要的类型。另外,如果值可能包含逗号,那么您可能需要使用不同的分隔符。
关于sql - 是否可以从一对多关系中的每一列获取最新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15276082/