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|
我可以将一列作为行。任何人都可以帮助实现上述目标
答案 0 :(得分: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
答案 1 :(得分: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
结果
答案 2 :(得分:0)
我不确定您要对此数据做什么。您是在寻找单个字符串,还是在寻找Column_B中的数据以放入每个名称的列(Column_A)?
如果是这样,你可以使用PIVOT语句(如果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
这将给出以下结果集:
如果您愿意,甚至可以根据需要制作一个大字符串:
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
这会得到以下结果: