2017-05-08 107 views
-2

所以我有一個表有以下的列:重新安排表中TSQL

Type Test Min  Max 
----------------------------- 
    1  a  1  2 
    1  b  Null Null 
    2  a  0  Null 
    2  b  Null  1 

試圖讓所有的人都喜歡這個

Type Test1 Test1 min Test1max Test2 Test2min Test2max 
------------------------------------------------------------ 
1  a  1   2  b  Null  Null 
2  a  0   Null  b  Null  1 

使用unpivot的第一次嘗試之前,我用支點,但它仍然給重複的測試和刪除任何幫助,這是非常讚賞 需要空值以及顯示以及

Select type, result 
(
From 
Select type, min 
From table t 
) 
Unpivot 
(result for minmax in (min1) 
) 

選擇 感謝

+1

編輯你的問題,顯示你有查詢學嘗試使用'pivot'結束。 –

回答

0

使用row_number()和有條件聚集:

select 
    [Type] 
    , Test_1  = max(case when rn = 1 then Test end) 
    , Test_1_Min = max(case when rn = 1 then Min end) 
    , Test_1_Max = max(case when rn = 1 then Max end) 
    , Test_2  = max(case when rn = 2 then Test end) 
    , Test_2_Min = max(case when rn = 2 then Min end) 
    , Test_2_Max = max(case when rn = 2 then Max end) 
from (
    select * 
    , rn = row_number() over (partition by [Type] order by [Test]) 
    from t 
) as s 
group by s.Type 

rextester演示:http://rextester.com/BKL48976

回報:

+------+--------+------------+------------+--------+------------+------------+ 
| Type | Test_1 | Test_1_Min | Test_1_Max | Test_2 | Test_2_Min | Test_2_Max | 
+------+--------+------------+------------+--------+------------+------------+ 
| 1 | a  |   1 | 2   | b  | NULL  | NULL  | 
| 2 | a  |   0 | NULL  | b  | NULL  | 1   | 
+------+--------+------------+------------+--------+------------+------------+ 
+0

我有多種類型(超過15)和測試(超過10),有沒有更簡單的方法呢? – Anonymous

0
select * 
from table t1 
join table t2 
    on t1.type = t2.type 
and t1.test < t2.test 
+0

我需要返回空值 – Anonymous

+0

這將返回示例數據集中的所有行。你有'type'或'test'爲null的行嗎? –

+0

發佈的數據中沒有空值。 – Paparazzi