SQL Server中1个表中每列的唯一结果

时间:2016-08-20 09:00:29

标签: sql sql-server unique distinct sql-server-2014

使用SQL Server 2014,我有一个非常大的表格,我需要获得每列的独特项目列表,我不需要彼此考虑。同样如果我将不同表中的每一列分开。但我需要在一个表中得到结果。

初始数据示例:

 Project   | Status    | Employees |
 -----------------------------------
 Project 1 |   Active  |     10    |  
 Project 2 |   Closed  |     10    | 
 Project 3 |   Closed  |     20    | 
 Project 1 |   Active  |     20    | 
 Project 2 |   Closed  |     20    | 

请求的数据,我只需要获得每列的唯一结果。

 Project   | Status    | Employees | 
 -----------------------------------
 Project 1 |   Active  |     10    |  
 Project 2 |   Closed  |     20    | 
 Project 3 |           |           | 
           |           |           | 

如果可能希望获得语法帮助。

1 个答案:

答案 0 :(得分:1)

这很痛苦,因为结果集不是关系形式的:每行中的列彼此不相关。但是,您可以使用row_number()full outer join或聚合:

来实现
select p.project, s.status, e.employees
from (select project, row_number() over (order by (select null)) as seqnum
      from t
      group by project
     ) p full outer join
     (select status, row_number() over (order by (select null)) as seqnum
      from t
      group by status
     ) s
     on p.seqnum = s.seqnum full outer join
     (select employees, row_number() over (order by (select null)) as seqnum
      from t
      group by project
     ) e
     on e.seqnum = coalesce(p.seqnum, s.seqnum);