2013-04-04 54 views
2

創建樞腳本我有一個表像需要在Sybase

ID  ENVI    SERVER    GROUP   ACTIVE 
==  ====    ======    ======   ====== 
1  Developent  AREGION_1   A    1 
2  Developent  AREGION_2   A    1 
3  Developent  AREGION_3   A    1 
4  Developent  BREGION_1   B    1 
5  Developent  BREGION_2   B    1 
6  Developent  BREGION_3   B    1 
7  Developent  CREGION_1   C    1 
8  Developent  CREGION_3   C    1 
9  Developent  A1REGION    A    1 
10  Developent  A2REGION    A    1 
11  Developent  ABCREGION   A    1 

我需要寫的輸入參數ENVI一個SP將返回的結果類似下面

ENVI    A    B    C 
====    =========  =========  ========= 
Development   AREGION_1  BREGION_1  CREGION_1 (All servers Ending with _1) 
Development   AREGION_2  BREGION_2     (All servers Ending with _2) 
Development   AREGION_3  BREGION_3  CREGION_3 (All servers Ending with _3) 
Development   A1REGION  
Development   A2REGION  
Development   ABCREGION 

條件 所有以_結尾的服務器都應該以第一個排序順序排列。 如果任何一列對於該字段應該爲空或空的行沒有值。 在任何組下的任何具有隨機名稱的服務器都必須放置在該組下。

請幫我創造了SP提前

回答

0

這是一個聚集查詢

感謝,雖然最終結果不包括匯聚一列(修改後的服務器名稱)。

select envi, 
     max(case when group = 'A' then server end) as A, 
     max(case when group = 'B' then server end) as B, 
     max(case when group = 'C' then server end) as C 
from t 
group by envi, 
     (case when server like '%[_]%' and server not like '%[_]%[^0-9]%' 
       then left(server, charindex('_', server) - 1) 
       else server 
      end) 

like邏輯查找具有下劃線,只有有下劃線後的數字的服務器名稱。

2

你沒有指定你正在使用的sybase版本,這個答案假設你有一個可以訪問窗口函數的版本。 Sybase沒有PIVOT功能,因此您必須使用帶有CASE表達式的聚合函數來複制它。

下面的代碼應該得到的結果是你想要的:

select envi, 
    max(case when serverGroup = 'A' then server end) as A, 
    max(case when serverGroup = 'B' then server end) as B, 
    max(case when serverGroup = 'C' then server end) as C 
from 
(
    select envi, 
    server, 
    serverGroup, 
    case 
     when frn > rn then frn 
     else rn 
    end rn  
    from 
    (
    select envi, 
     server, 
     serverGroup, 
     case 
     when charindex('_', SERVER) = 0 
     then 0 
     else substring(SERVER, charindex('_', SERVER)+1, len(SERVER)) 
     end frn, 
     row_number() over(partition by envi, serverGroup 
         order by substring(SERVER, charindex('_', SERVER), len(SERVER)+1)) rn 
    from ytable 
) d 
) x 
group by envi, rn 
order by rn; 

SQL Fiddle with Demo。注意:演示在SQL Server上。

這給出結果:

|  ENVI |   A |   B |   C | 
-------------------------------------------------- 
| Developent | AREGION_1 | BREGION_1 | CREGION_1 | 
| Developent | AREGION_2 | BREGION_2 | (null) | 
| Developent | AREGION_3 | BREGION_3 | CREGION_3 | 
| Developent | A1REGION | (null) | (null) | 
| Developent | A2REGION | (null) | (null) | 
| Developent | ABCREGION | (null) | (null) | 
+0

+1使用旋轉功能,以出支點 – rahularyansharma 2013-04-04 10:50:22