组合来自多个表的行

时间:2018-05-29 11:46:29

标签: sql sql-server reporting-services

我正在考虑在SSRS中撰写报告,我试图让一个专栏按照我的意愿工作。我们的数据库设置有3个表,一个带有员工姓名和ID(员工),一个带有角色名称和ID(角色),还有一个动态表,用于链接staffID和RoleID(链接):

员工表

StaffName | StaffID
----------+--------
Tom       | 101
Dick      | 102
Harry     | 103

链接表

StaffID | RoleID
--------+-------
101     | 1
102     | 2
102     | 3
103     | 3
103     | 4

角色表

RoleID | RoleName
-------+---------
1      | a
2      | b
3      | c
4      | d

我正在尝试将其压缩为输出以放入SSRS,如下表所示:

输出表

StaffName | RoleName
----------+---------
Tom       | a
Dick      | b, c
Harry     | c, d

不幸的是,由于它们被链接起来,我发现很难获得所需的输出。到目前为止,我有一个表以正确的方式输出RoleID,但不是RoleNames,如下所示:

StaffID | RoleIDs | Rolenames
--------+---------+----------
101     | 1       | a
102     | 2, 3,   | b
102     | 2, 3,   | c
103     | 3, 4,   | c
103     | 3, 4,   | d

为此,我使用此代码:

SELECT DISTINCT 
    Links2.StaffID,
    substring(
    (
        SELECT 
            CAST (Links1.RoleID AS varchar(max)) + ', ' AS [text()]
        FROM Links AS Links1
        WHERE Links1.StaffID = Links2.StaffID
        ORDER BY Links1.StaffID
        For XML PATH ('')
    ), 1, 1000) AS RoleIDs,
    substring(
    (
        SELECT
        CAST (Roles1.RoleName AS varchar(max)) + ', ' as [text()]
        FROM Roles AS Roles1
        WHERE Roles1.RoleID = Roles2.RoleID
        ORDER BY Role1.RoleID
        FOR XML PATH('')
    ), 1, 1000) AS RoleNames
FROM Links AS Links2
LEFT OUTER JOIN Roles Roles2
ON Roles2.RoleID = Links2.RoleID

如果格式化已关闭,任何帮助都会受到赞赏并道歉。

由于 罗布

3 个答案:

答案 0 :(得分:0)

@Rob,尝试以下解决方案,

select s.staffName,
         STUFF((SELECT ', ' + CAST(r.RoleName AS VARCHAR(10)) [text()]
         FROM Roles r1  
         inner join Links l on l.StaffID = s.StaffID
         inner join Roles r on r.RoleID = l.RoleID
         WHERE r1.RoleID = r.RoleID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
from Staff s

答案 1 :(得分:0)

我还没有在SQL Server上尝试查询,但这种方法应该可行。 创建Temp表并在其中插入Staff和Links相关数据。然后使用Roles表在Temp表上放置一个内连接以获得所需的结果:

CREATE TABLE #TempStaffAndLink
  (
    StaffId INT,
    StaffName VARCHAR(30), 
    RoleId INT
   );


INSERT INTO #TempStaffAndLink
SELECT Staff.StaffId, Staff.StaffName, Link.RoleId from Staff 
INNER JOIN Link
ON Staff.StaffId = Link.StaffId;

这将在一个具有StaffName的表中为您提供StaffId和RoleId。现在在Roles表上放置一个内连接来获取RoleName:

SELECT #TempStaffAndLink.StaffName as StaffName, Role.RoleName as RoleName
FROM #TempStaffAndLink
INNER JOIN Role
ON #TempStaffAndLink.RoleId = Role.RoleId;

答案 2 :(得分:0)

试试这个..

select StaffName ,string_agg(RoleName,',') as RoleName
from (
select a.StaffName,a.StaffID,b.RoleID,c.RoleName
from Staff_table a 
left outer join Links_table b
on a.StaffID = b.StaffID
left outer join Roles_table c
on b.RoleID = c.RoleID 
)x
group by 1