仅选择不同的列

时间:2015-08-10 07:48:58

标签: sql sql-server select sql-server-2005 distinct

我有表T并希望只选择不同的列(字段之间没有相关性)

F1  F2  F3
 1   A   AA
 1   B   BB
 2   B   CC
 2   C   DD
 2   C   EE
 3   C   EE

期望的输出

 F1   F2   F3
 1    A    AA
 2    B    BB
 3    C    CC
 null null DD
 null null EE

我试试

select T.F1, T1.F2 from
(select distinct F1, row_num() rn from T) T
left join (select distinct F2, row_num() rn from T) T1 on T.rn=T1.rn1
left join etc...

可以更简单吗?

2 个答案:

答案 0 :(得分:1)

  

输入:

F1  F2
1   A
1   B
2   B
2   C
2   C
3   C
     

期望的输出:

F1  F2
1   A
2   B
3   C

根据提供的输入,这也会产生所需的输出:

SELECT F1, MIN(F2) AS F2
FROM T
GROUP BY F1;

答案 1 :(得分:1)

**Example for two columns.** 
SELECT t1.f1, t2.f2
    FROM
    (
    SELECT ROW_NUMBER() OVER(ORDER BY f1) AS num, f1 FROM
    (
    SELECT DISTINCT f1 FROM T
    ) AS t1
    ) AS t1
    FULL JOIN 
    (
    SELECT ROW_NUMBER() OVER(ORDER BY f2) AS num, f2 FROM
    (
    SELECT DISTINCT f2 FROM T
    ) AS t2
    ) AS t2 ON t2.num = t1.num