通过将某些值组合到列中来展平表行

时间:2014-03-14 16:10:10

标签: sql case flatten

我尝试构建一个用于报告目的的视图,并且通过将几个值组合到列中而难以展平结果以通常将多行显示为单行。每个组织都有两个管理员,并希望将它们显示在同一行中。查询如下:

SELECT dbo.Organization.OrganizationName,
       CASE 
        WHEN (dbo.OrganizationUser.AdminOrder = 1) 
        THEN dbo.OrganizationUser.UserID 
        ELSE '' 
       END AS Admin1,
       CASE 
        WHEN (dbo.OrganizationUser.AdminOrder = 2) 
            THEN dbo.OrganizationUser.UserID 
        ELSE '' 
       END AS Admin2
FROM   dbo.Organization 
INNER JOIN dbo.OrganizationUser 
    ON dbo.OrganizationUser.OrganizationId = dbo.Organization.OrganizationId
WHERE  dbo.OrganizationUser.UserType = 'ADMIN'  

问题是,我得到两行看起来像

Organization1 - User1   - <empty>
Organization1 - <empty> - User2

我无法让行合并。

1 个答案:

答案 0 :(得分:0)

这是一项非常标准的操作;你只是错过了它的后半部分。您需要一个执行合并步骤的周围查询:

select foo.orgname, max(foo.Admin1), max(foo.Admin2)
from   (SELECT dbo.Organization.OrganizationName as orgname,
               CASE WHEN (dbo.OrganizationUser.AdminOrder = 1) THEN dbo.OrganizationUser.UserID ELSE '' END AS Admin1,
               CASE WHEN (dbo.OrganizationUser.AdminOrder = 2) THEN dbo.OrganizationUser.UserID ELSE '' END AS Admin2
        FROM   dbo.Organization 
         INNER JOIN dbo.OrganizationUser ON dbo.OrganizationUser.OrganizationId = dbo.Organization.OrganizationId
        WHERE  dbo.OrganizationUser.UserType = 'ADMIN') foo
group  by foo.orgname