2015-04-15 46 views
0
Column_A  Column_B 
Akash.Bansal Deactivate_User 
Akash.Bansal Deactivate_Int_User 

我想作爲輸出:轉換列數據的行數據

Akash.Bansal | Deactivate_User |Deactivate_Int_User |Delete_User |Delete_Inter_User| 

我能夠做一列列。任何一個都可以幫助您獲得高於012的配置

回答

0

我不知道你想和這個數據做什麼。你正在尋找一個單一的字符串,或者你是否正在尋找來自Column_B的數據,以便將它放入每個名稱的列(Column_A)中?

如果是這樣,你可以使用這個PIVOT語句(if Column_B選項是有限的)

declare @Example table (
    Column_A nvarchar(20), 
    Column_B nvarchar(20) 
) 

insert into @Example values ('Akash.Bansal','Deactivate_User') 
insert into @Example values ('Akash.Bansal','Deactivate_Int_User') 
insert into @Example values ('Akash.Bansal','Delete_User ') 
insert into @Example values ('Akash.Bansal','Delete_Inter_User') 
insert into @Example values ('John.Doe','Deactivate_User') 
insert into @Example values ('Jane.Doe','Deactivate_Int_User') 
insert into @Example values ('Jane.Doe','Delete_User ') 
insert into @Example values ('Jane.Doe','Delete_Inter_User') 

select 
    * 
from 
    @Example 
PIVOT 
(
    MIN(Column_B) 
    FOR Column_B IN (Deactivate_User,Deactivate_Int_User,Delete_User,Delete_Inter_User) 
) pivotTable 

這將給以下結果集:

Resultset1

你甚至可以,如果你希望,如果你也需要這樣做,從這個大字符串:

select 
    pivotTable.Column_A, 
    STUFF(
     COALESCE(' | ' + NULLIF(Deactivate_User, ''), '') + 
     COALESCE(' | ' + NULLIF(Deactivate_Int_User, ''), '') + 
     COALESCE(' | ' + NULLIF(Delete_User, ''), '') + 
     COALESCE(' | ' + NULLIF(Delete_Inter_User , ''), ''), 
     1, 3, '') AS String 
from 
    @Example 
PIVOT 
(
    MIN(Column_B) 
    FOR Column_B IN (Deactivate_User,Deactivate_Int_User,Delete_User,Delete_Inter_User) 
) pivotTable 

這將使以下結果:

Resultset2

+0

感謝所有幫助:) – user3844864

2

您可以通過使用STUFF()函數來實現。嘗試這樣的事情,

CREATE TABLE TestUsr(Column_A VARCHAR(50), Column_B VARCHAR(50)) 

INSERT INTO TestUsr(Column_A, Column_B) VALUES 

('Akash.Bansal', 'Deactivate_User'), 
('Akash.Bansal', 'Deactivate_Int_User') 

SELECT Column_B FROM 
(
    SELECT ROW_NUMBER() OVER(PARTITION BY Column_A ORDER BY Column_A) RN, 
    Column_B = Column_A + ' | ' + 
    STUFF((SELECT ' | ' + Column_B 
    FROM TestUsr b FOR XML PATH('')), 1, 2, '') + ' | ' 
    FROM TestUsr a 
) AS E WHERE RN = 1 

Sql Fiddle Demo

0

試試這個

WITH cte 
      AS (SELECT Column_A , 
         Column_B 
       FROM  (VALUES ('Akash.Bansal', 'Deactivate_User'), 
         ('Akash.Bansal', 'Deactivate_Int_User'), 
         ('Akash.Bansal', 'Delete_User'), 
         ('Akash.Bansal', 'Delete_Inter_User'), 
         ('John.Dohn', 'Create'), 
         ('John.Dohn', 'Update') 

         ) AS T (Column_A, Column_B) 
      ) 
    SELECT A.Column_A , 
      SUBSTRING((SELECT ' ' + B.Column_B + ' |' 
         FROM cte AS B 
         WHERE A.Column_A = B.Column_A 
         FOR 
         XML PATH('') 
        ), 2, 1000) AS String, 
         COUNT(*) Cnt 
    FROM cte AS A  
    GROUP BY A.Column_A 

結果

enter image description here