2017-05-08 77 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