基于Id的连接将多个列组合成一行的查询

时间:2018-06-18 19:05:34

标签: sql sql-server tsql join pivot

鉴于下表T:

------------------------------
|  Person | PermissionTypeId |
------------------------------
|  Jon   |       1           |
------------------------------
|  Jon   |       2           |
------------------------------
|  Adam  |       1           |
------------------------------

表P:

------------------------------
| Id   | PermDescription     |
------------------------------
|  1   |  Can Access Reports |             
------------------------------
|  2   |  Can Access Locker  |         
------------------------------

假设我想编写一个返回一行Jons权限的查询,如下所示:

------------------------------------------------------
| Person   | Can Access Reports | Can Access Locker  |
------------------------------------------------------
|  Jon     |      true          |      true          |
------------------------------------------------------

如果存在与用户关联的PermissionTypeId,则存在true。并且 false 存在于没有的地方。因此,Adams查询将返回:

-----------------------------------------------------
| Person   | Can Access Reports | Can Access Locker |
----------------------------------------------------
|  Adam    |      true          |        false      |
-----------------------------------------------------

如何编写以下返回此行的查询?

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

declare @T table(person varchar(10), PermissionType int);
insert into @T values
('Jon', 1),
('Jon', 2),
('Adam', 1);
declare @P table(id int, PermDescription varchar(100));
insert into @P values
(1, 'Can Access Reports'),
(2, 'Can Access Locker');

select person,
       case when [Can Access Reports] is null then 'false' else 'true' end [Can Access Reports],
       case when [Can Access Locker] is null then 'false' else 'true' end [Can Access Locker]
from (
    select t.person, t.permissiontype, p.permdescription
    from @T t join @p p on t.PermissionType = p.id
) unpvt pivot (
    max(permissiontype) for permdescription in ([Can Access Reports],[Can Access Locker])
) pvt

答案 1 :(得分:0)

您可以像下面一样进行转动 See working demo

 select *
    from
     (
      select 
          t.Person,
          p1.PermDescription,
          data = case when max(p2.id) is null then N'false' else N'true' end
      from 
          t cross join  P p1 
           left join P p2
           on p2.id=t.PermissionTypeId and p2.id=p1.id
       group by t.Person,
          p1.PermDescription
       )   src
       pivot 
       ( max(data) for PermDescription in ([Can Access Locker],[Can Access Reports]))p