我在创建数据透视查询方面遇到了一些问题:
我有这些数据:
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
但我无法弄清楚如何构建语句来获得这个。
答案 0 :(得分: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;
这也可以使用带有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;