2013-05-06 70 views
0

我有这样的SQL结果TSQL合并和分组值

color red  AA 
color red  BB 
color red  CC 
color blue DD 
color blue EE 

有没有办法通过柱合并,得到如下结果?

color red  AA 
       BB 
       CC 
     blue DD 
       EE 

回答

6

这是典型的东西,你会做你的应用程序的表现层,但如果你想这样做在SQL中,你可以使用row_number()

select 
    case when col1rn = 1 then col1 else '' end col1, 
    case when col2rn = 1 then col2 else '' end col2, 
    col3 
from 
(
    select col1, col2, col3, 
    row_number() over(partition by col1 order by col1, col2, col3) col1rn, 
    row_number() over(partition by col1, col2 order by col1, col2, col3) col2rn 
    from yt 
) d; 

SQL Fiddle with Demo。一个case可以空出来作为必要

| COL1 | COL2 | COL3 | 
----------------------- 
| color | blue | DD | 
|  |  | EE | 
|  | red | AA | 
|  |  | BB | 
|  |  | CC | 
| test | blue | CC | 
|  | red | AA | 
|  |  | BB | 
1

在这里,我们使用的是排名功能找到你的冗余数据,然后:你将与你的查询替换from yt,给人的结果。还要注意的是,我们正在处理多个“类别”或“组”,或者您正在使用真实数据进行分区的任何内容(在此处显示为列ab)。

;with cte as (
    select 'color' as a, 'red' as b, 'AA' as c 
    union all select 'color', 'red', 'BB' 
    union all select 'color', 'red', 'CC' 
    union all select 'color', 'blue', 'DD' 
    union all select 'color', 'blue', 'EE' 
    union all select 'smell', 'bad', 'AA' 
    union all select 'smell', 'bad', 'BB' 
    union all select 'smell', 'bad', 'CC' 
    union all select 'smell', 'good', 'DD' 
    union all select 'smell', 'good', 'EE' 
) 
select case when row_number() over (partition by a order by b, c) = 1 then a else '' end as ColA 
    , case when row_number() over (partition by a, b order by c) = 1 then b else '' end as ColB 
    , c as ColC 
from cte 
order by a, b, c 

这将产生以下结果:

ColA ColB ColC 
----- ---- ---- 
color blue DD 
      EE 
     red AA 
      BB 
      CC 
smell bad AA 
      BB 
      CC 
     good DD 
      EE