2011-03-02 156 views
2

我有一個表count與屬性選擇列的基礎上最大值

  • COUNT1
  • COUNT2
  • 共3個記錄
  • count4
  • count5

我想選擇一個具有最大值的列。我怎麼做?

計數代表頁面命中,我想選擇一個具有最大命中並顯示它的列。

+0

你爲什麼要把列命名爲'count1','count2'等等?他們是否表達了某種意義? – 2011-03-02 07:50:51

+0

我不認爲這些是列的實際名稱.... – PedroC88 2011-03-02 07:54:14

+1

kst - 一旦問題得到解答,通常會在答案中打勾以表明它已被接受。這在某種意義上「關閉」了關於答案的 – RichardTheKiwi 2011-03-02 10:52:51

回答

5

您可以使用一個雙重嵌套子查詢

select 
    (select max(count1) 
    from (
    select count1 union all 
    select count2 union all 
    select count3 union all 
    select count4 union all 
    select count5) X) as MaxCount 
from tbl 
+0

「union all」有什麼用途? – 2011-03-02 08:04:46

+0

@Uw概念:{subquery} UNION ALL {subquery} - >創建一個由兩個子查詢中的所有記錄組成的派生表。 – RichardTheKiwi 2011-03-02 08:16:32

+0

非常好,非常感謝您提供的信息! – 2011-03-02 08:20:02

0

有幾種方法,涉及PIVOTTemp Table,但我認爲最容易理解的是使用Case爲此。

SELECT 
    CASE 
     WHEN count1 >= count2 AND count2 >= count3 AND count1 >= count4 AND count1 >= count5 THEN count1 
     WHEN count2 >= count3 AND count2 >= count4 AND count2 >= count5 THEN count2 
     WHEN count3 >= count4 AND count3 >= count5 THEN count3 
     WHEN count4 >= count5 THEN count4 
     ELSE count5 
    END AS highestCount 
+1

注意:如果任何計數爲NULL,那麼您的鏈將被破壞。 – RichardTheKiwi 2011-03-02 08:00:46

+0

感謝您指出這一點,在列周圍使用COALESCE(countX,0)可能有所幫助 – 2011-03-02 08:03:48

0
select MAX(max_count) FROM 
    (
    select count1 as max_count from count 
    UNION 
    select count2 as max_count from count 
    UNION 
    select count3 as max_count from count 
    UNION 
    select count4 as max_count from count 
    UNION 
    select count4 as max_count from count 
    ) 

我不會建議使用選擇,因爲它需要很多的時候產生相同的。觸發器會更好