2016-09-15 121 views
1

我有一個表格,列col1col2,col3。在每一行中,只有其中一個值不爲空。我想找到col1col2col3(顯然來自三個單獨的行)的最新值,其中這些不是NULL查找MySQL表中每個列的最後一個非空值?

這裏是一個模式:

  • col1 - INT
  • col2 - INT
  • col3 - INT
  • timestamp - DATETIME

假設我有這樣的數據:

+------+------+------+------------------+ 
| col1 | col2 | col3 | timestamp  | 
+------+------+------+------------------+ 
| 1 | NULL | NULL | 15/09/2016 10:55 | 
| NULL | 2 | NULL | 15/09/2016 10:56 | 
| NULL | NULL | 3 | 15/09/2016 10:57 | 
| 4 | NULL | NULL | 15/09/2016 10:58 | 
+------+------+------+------------------+ 

我想要的結果如下:

+------+------+------+ 
| col1 | col2 | col3 | 
+------+------+------+ 
| 4 | 2 | 3 | 
+------+------+------+ 

我如何編寫一個查詢來做到這一點?

+1

最新相對的是什麼? –

+0

@vkp你可以假設它按降序排列的'timestamp'列。 – think123

+1

你可以提供樣品輸入和輸出... – Teja

回答

2
select 
    (select col1 from tbl where col1 is not null order by timestamp desc limit 1) as col1, 
    (select col2 from tbl where col2 is not null order by timestamp desc limit 1) as col2, 
    (select col3 from tbl where col3 is not null order by timestamp desc limit 1) as col3 
1

假設你有一列,如timestamp指定排序,那麼你就可以得到每個使用最後的ID:

select max(case when col1 is not null then timestamp end) as ts1, 
     max(case when col2 is not null then timestamp end) as ts2, 
     max(case when col3 is not null then timestamp end) as ts3 
from t; 

然後你可以得到你想要使用join行:

select t.* 
from t join 
    (select max(case when col1 is not null then timestamp end) as ts1, 
      max(case when col2 is not null then timestamp end) as ts2, 
      max(case when col3 is not null then timestamp end) as ts3 
     from t 
    ) tt 
    on t.timestamp in (ts1, ts2, ts3) 
0

使用以下命令:

select @a:=null, @b:=null, @c:=null; 
select A,B,C from (
    select @a:=coalesce(A,@a) as A, @b:=coalesce(B,@b) as B, @c:=coalesce(C,@) as C time 
    from yourtable 
    order by time asc 
) as y order by time desc limit 1; 

更新了帖子:

SELECT DISTINCT (
    SELECT col1 
    FROM demo 
    WHERE IFNULL(col1, 0) != 0 
    ORDER BY timestamp DESC 
    LIMIT 1 
) col1, (
    SELECT col2 
    FROM demo 
    WHERE IFNULL(col2, 0) != 0 
    ORDER BY timestamp DESC 
    LIMIT 1 
) col2, (
    SELECT col3 
    FROM demo 
    WHERE IFNULL(col3, 0) != 0 
    ORDER BY timestamp DESC 
    LIMIT 1 
) col3 
FROM demo 

表結構:

col1 col2 col3 timestamp 
    1  2  8 2016-09-02 10:00:00 
    0  4  10 2016-09-04 12:00:00 

返回:

col1 col2 col3 
    1  4  10 
+0

您的查詢不適合我...請問您可以將它改寫爲「col1」,「col2」和「col3」嗎? – think123

+0

嘗試根據你的改變列。不用擔心,如果它不起作用。我會解決這個問題。 –

+0

將排序改爲'desc',這應該起作用。 –

相關問題