2

使用这个数据集:

| 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上启动。

4

2 回答 2

2

这是一种适用于许多 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

一些数据库可能更喜欢toprecnum = 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

这将具有将值转换为字符串的副作用。您可以转换回您想要的类型。此外,如果值可能包含逗号,那么您可能需要使用不同的分隔符。

于 2013-03-07T16:18:01.507 回答
0

这是一种适用于许多 SQL 方言的方法,无需子查询且仅产生一行输出。

SELECT f1.value1,f3.value2,f5.value3 FROM FUNTIMES f1 
LEFT JOIN funtimes f2 ON
f1.recdt<f2.recdt AND f2.value1 IS NOT NULL
JOIN funtimes f3 ON f1.ptid=f3.ptid
LEFT JOIN funtimes f4 ON
f3.recdt<f4.recdt AND f4.value2 IS NOT NULL
JOIN funtimes f5 ON f1.ptid=f5.ptid
LEFT JOIN funtimes f6 ON
f5.recdt<f6.recdt AND f6.value3 IS NOT NULL
WHERE f1.value1 IS NOT NULL AND f2.value1 IS NULL
AND f3.value2 IS NOT NULL AND f4.value2 IS NULL
AND f5.value3 IS NOT NULL AND f6.value3 IS NULL;

与上面的比较:http ://www.sqlfiddle.com/#!2/9ee9a/34

于 2013-03-07T16:46:17.083 回答