2013-05-06 77 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