TSQL合并&分组值

时间:2013-05-06 14:00:47

标签: sql-server tsql merge

我有这个sql结果

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

有没有办法按列合并,以获得以下结果?

color    red     AA
                 BB
                 CC
         blue    DD
                 EE

2 个答案:

答案 0 :(得分: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。您可以将from yt替换为您的查询,并给出结果:

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

答案 1 :(得分:1)

这里我们使用排名功能查找您的冗余数据,然后case可以根据需要将其删除。另请注意,我们正在处理多个“类别”或“群组”或您在实际数据中进行分区的任何内容(此处显示为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