2013-03-07 24 views
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月,02日,結果是這樣的:

| ID | VALUE1 | VALUE2 | VALUE3 | 
----------------------------------- 
| 1-01 |  3 |  2 |  3 | 


的模式已經開始sqlfiddle的人感興趣。

+0

SQL版本,你使用的是哪個? – 2013-03-07 16:15:40

+0

@NitinMidha MS SQL Server 2008 R2 – afuzzyllama 2013-03-07 16:17:22

回答

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 

這將有旋轉值到字符串的副作用。你可以回到你想要的類型。另外,如果這些值可能包含逗號,那麼您會希望使用不同的分隔符。

+1

運行那麼多的子查詢是否存在性能問題? – afuzzyllama 2013-03-07 16:19:55

+1

@afuzzyllama。 。 。如果你有'ptid,recdt'的索引,那麼性能不應該是一個大問題。每個子查詢將通過將相同記錄加載到內存並掃描它們來解決;一旦第一個子查詢運行,記錄就已經存在於緩存中。 – 2013-03-07 16:23:28

+0

感謝您的洞察!我想這樣做,但沒有足夠的背景知道這樣的子查詢是否是要走的路。 – afuzzyllama 2013-03-07 16:27:33

0

這是一個可以在許多SQL語言中使用而無需子查詢並僅生成一行輸出的aproach。

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

相關問題