我不确定这是否称为“透视”。
我的SQL 2005表 [CustromerRoles]中的数据 是这样的:
CustId RoleId 2 4 2 3 3 4 4 1 4 2
[角色] 表:
RoleId Role 1 Admin 2 Manager 3 Support 4 Assistant
我想创建一个这样的视图:
SELECT * FROM [MYVIEW]将为我提供以下数据:
1和0将是位,因此我可以在UI显示屏上显示带有复选框的网格。
CustId Admin Manager Support Assistant 2 0 0 1 1 3 0 0 0 1 4 1 1 0 0
到目前为止,我还不知道如何去做。
试试这个:
SELECT CustId, SUM(ISNULL(Admin,0)) AS Admin, SUM(ISNULL(Manager,0)) AS Manager, SUM(ISNULL(Support,0)) AS Support, SUM(ISNULL(Assistant,0)) AS Assistant FROM ( SELECT cr.CustId, cr.RoleId, Role, 1 AS a FROM CustromerRoles cr INNER JOIN Roles r ON cr.RoleId = r.RoleId ) up PIVOT (MAX(a) FOR Role IN (Admin, Manager, Support, Assistant)) AS pvt GROUP BY CustId
经过测试。它给出您想要的相同结果。