0

我在创建数据透视查询时遇到了一些问题:

我有这个数据:

DECLARE @UserAccess TABLE
(
    userName char(255),
    project char(255),
    role char(255)
);

userName  project  role
--------  -------  ----
ado       BI       U
aga       BI       D
aga       BI       U
mim       BI       A
mim       BI       U
ado       BID      D
ado       BID      U
aga       BID      D
aga       BID      U
mim       BID      A
mim       BID      D
mim       BID      U

我想要的是这样的:

User    BI    BID
-----   ---   ---
ado     U     DU
aga     DU    DU
mim     AU    ADU

但我不知道如何构造语句来得到这个。

4

1 回答 1

1

首先,您需要将 连接roles成一行,然后您可以应用 PIVOT 函数:

select username, BI, BID
from
(
  select username, project, 
    STUFF((SELECT distinct '' + t.[role]
         from UserAccess t
         where u.username = t.username
           and u.project = t.project
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,0,'') role
  from UserAccess u
) d
pivot
(
  max(role)
  for project in (BI, BID)
) piv;

请参阅SQL Fiddle with Demo

这也可以使用带有CASE表达式的聚合函数来编写:

;with cte as
(
  select username, project, 
    STUFF((SELECT distinct '' + t.[role]
         from UserAccess t
         where u.username = t.username
           and u.project = t.project
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,0,'') role
  from UserAccess u
)
select username,
  max(case when project = 'BI' then role end) BI,
  max(case when project = 'BID' then role end) BID
from cte
group by username;

请参阅带有演示的 SQL Fiddle

于 2013-04-05T15:02:13.737 回答