使用此数据集:
| 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启动了架构。
答案 0 :(得分: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
某些数据库可能更喜欢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
这会产生将值转换为字符串的副作用。你可以回到你想要的类型。此外,如果值可能包含逗号,那么您可能希望使用不同的分隔符。
答案 1 :(得分: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;