2015-04-16 58 views
1

我有一個表有幾列,每一行我想最大:逐行最大

-- Table: 
+----+----+----+----+----+ 
| ID | C1 | C2 | C3 | C4 | 
+----+----+----+----+----+ 
| 1 | 1 | 2 | 3 | 4 | 
| 2 | 11 | 10 | 11 | 9 | 
| 3 | 3 | 1 | 4 | 1 | 
| 4 | 0 | 2 | 1 | 0 | 
| 5 | 2 | 7 | 1 | 8 | 
+----+----+----+----+----+ 


-- Desired result: 
+----+---------+ 
| ID | row_max | 
+----+---------+ 
| 1 |  4 | 
| 2 |  11 | 
| 3 |  4 | 
| 4 |  2 | 
| 5 |  8 | 
+----+---------+ 

兩個或三個欄,我只是把它寫出iifCASE聲明。

select ID 
    , iif(C1 > C2, C1, C2) row_max 
from table 

但隨着更多的列,這會變得很麻煩。有沒有一種很好的方式來獲得這種按行最大值?在R中,這被稱爲「並行最大值」,所以我喜歡類似於

select ID 
    , pmax(C1, C2, C3, C4) row_max 
from table 
+0

看看支點HTTP: //stackoverflow.com/questions/13372276/simple-way-to-transpose-columns-and-rows-in-sql –

回答

8

那麼如何將數據轉換爲無效數據以獲得結果呢?你說過tsql而不是SQL Server的版本。在SQL Server 2005 +,你可以使用CROSS APPLY到列轉換爲行,然後得到最大值爲每行:

select id, row_max = max(val) 
from yourtable 
cross apply 
(
    select c1 union all 
    select c2 union all 
    select c3 union all 
    select c4 
) c (val) 
group by id 

SQL Fiddle with Demo。請注意,這可以通過使用table value constructor縮寫。

這也可以在SQL Server通過UNPIVOT函數來完成:

select id, row_max = max(val) 
from yourtable 
unpivot 
(
    val 
    for col in (C1, C2, C3, C4) 
) piv 
group by id 

SQL Fiddle with Demo。兩個版本都給出了結果:

| id | row_max | 
|----|---------| 
| 1 |  4 | 
| 2 |  11 | 
| 3 |  4 | 
| 4 |  2 | 
| 5 |  8 | 
+0

是交叉應用整齊比樞軸? –

+0

@FabianBigler Pivot將數據行轉換爲列,這是相反的。它採用多列並將其變爲行以獲得最大值。 – Taryn

+0

我以爲你也可以使用unpivot而不是交叉應用 –

6

您可以使用下面的查詢:

SELECT id, (SELECT MAX(c) 
      FROM (
       SELECT c = C1 
       UNION ALL 
       SELECT c = C2 
       UNION ALL 
       SELECT c = C3 
       UNION ALL 
       SELECT c = C4 
      ) as x(c)) maxC 
FROM mytable 

SQL Fiddle Demo

1

一種方法是使用cross apply

select t.id, m.maxval 
from table t cross apply 
    (select max(val) as maxval 
     from (values (c1), (c2), (c3), (c4)) v(val) 
    ) m 
+1

爲什麼downvote?這和Giorgos的答案是迄今爲止最好的。 –

+2

不是我的投票,但爲什麼呢?仔細闡述爲什麼這個和Giorgos是迄今爲止最好的? – Taryn

+2

@bluefeet。 。 。您的答案需要彙總整個數據集。相關的子查詢和「交叉應用」只需要在少量數據中進行聚合。 –