2011-10-28 34 views
4

我有一個使用GREATEST()函數的MySQL查詢,我想在標準ANSI SQL中重寫它以在其他數據庫上運行。我知道大多數SQL數據庫都支持GREATEST,但我可能會在Hive中運行查詢,它支持像CASE這樣的東西,但不是最好的。在MySQL查詢中替換GREATEST()的標準SQL

任何人都可以想到一個優雅的方式來重寫這個查詢,而不使用GREATEST()

謝謝!

select 
greatest(play,play_25,play_50,play_75,play_100) as play, 
greatest(play_25,play_50,play_75,play_100) as play_25, 
greatest(play_50,play_75,play_100) as play_50, 
greatest(play_75,play_100) as play_75, 
play_100 as play_100 
from video_buckets 
+2

您可能希望看看http://stackoverflow.com/questions/6717127/how-to-find-the-min-value-among-multiple-col –

回答

2

這應該工作,雖然我不知道你是否可以把它稱爲 '優雅':

SELECT 
    CASE WHEN play_25 > play THEN play_25 ELSE play END AS play, 
    play_25, 
    play_50, 
    play_75, 
    play_100 
FROM (
    SELECT 
    play, 
    CASE WHEN play_50 > play_25 THEN play_50 ELSE play_25 END AS play_25, 
    play_50, 
    play_75, 
    play_100 
    FROM (
    SELECT 
     play, 
     play_25, 
     CASE WHEN play_75 > play_50 THEN play_75 ELSE play_50 END AS play_50, 
     play_75, 
     play_100 
    FROM (
     SELECT 
     play, 
     play_25, 
     play_50, 
     CASE WHEN play_100 > play_75 THEN play_100 ELSE play_75 END AS play_75, 
     play_100 
     FROM video_buckets 
    ) s 
) s 
) s 
+0

我認爲它對我來說足夠優雅,並且應該在Hive中工作。謝謝! –

4

這不會在MySQL工作,但validates as Full SQL-92

SELECT (SELECT MAX(c) 
     FROM (VALUES(play), 
         (play_25), 
         (play_50), 
         (play_75), 
         (play_100)) T (c)) AS play, 
     (SELECT MAX(c) 
     FROM (VALUES (play_25), 
         (play_50), 
         (play_75), 
         (play_100)) T (c)) AS play_25 
FROM video_buckets 
+0

你的[其他想法](http://stackoverflow.com/questions/7766921 /更新行,在表型上,子查詢上-SAM電子表格/ 7774262#7774262),它會在MySQL中工作嗎? –

+0

@AndriyM - 編號MySQL不支持這些對派生表中外部查詢的列的引用。 AFAIK派生表在整個查詢過程中需要保持靜態。 –

+0

我猜這不適用於MySQL。也許值得嘗試用UNION來重寫這個。 – Karolis