2016-07-29 45 views
0

我有一個表結構抓取最大值行明智在MySQL

ID Col_1 col_2 col_3 col_4 
1 34  23  45  32 
2 20  19  67  18 
3 40  10  76  86 

我在這裏想從COL_1,col_,col_3,col_4所以我的輸出看起來像

ID Col_1 col_2 col_3 col_4 max 
    1 34  23  45  32 45 
    2 20  19  67  18 67 
    3 40  10  76  86 86 

我的最大值嘗試使用

SELECT ID, MAX(col_1,col_2,col_3,col_4) as max 
FROM demo 
GROUP BY ID 

任何幫助將不勝感激。

+0

什麼是查詢的結果你寫的嗎? – Thijs

回答

1

您需要規範化表結構。試試這個

select ID, max(Col_1) as max_value from 
(
select ID, Col_1 from table 
union all 
select ID, Col_2 from table 
union all 
select ID, Col_3 from table 
union all 
select ID, Col_4 from table 
) as t group by ID 
+0

這個作品像魅力!由於 – Deepesh

1

你可能會嘗試這個

SELECT ID, col_1, col_2, col_3, col_4, 
GREATEST(col_1, col_2, col_3, col_4) AS max_value FROM table_name 
+0

謝謝!!! ......它的工作原理 – Deepesh

0

@Thijs給您參考,這是對應的輸出I得到。通過@Madhivanan第一次查詢的

enter image description here

查詢結果

enter image description here

從最初的兩種解決方案的查詢結果提供