Sql:从两个表生成矩阵具有多对多关系

时间:2018-01-21 21:37:16

标签: sql postgresql

我有3个表:droit,role和role_droit。我在droit和role之间有很多关系,而role_droit在关联表之间有很多关系。请在图下面找到。我将返回一个如下图所示的矩阵:结果2 如果我们之间有一个交集2个表 droit 角色我们将 1 其他 0 。我尝试了这个查询但是我在图表结果1

中得到了结果
SELECT matrix_view.droit_id,
    case when matrix_view.aid = 1 then haspair end as  "role A" ,
    case when matrix_view.aid = 2 then haspair end as  "role B" ,
    case when matrix_view.aid = 3 then haspair end as  "role C" ,
    case when matrix_view.aid = 4 then haspair end as  "role D"

        from (SELECT allRD.aid as aid, allRD.droit_id, max(case when RD.role_id is not null then 1 else 0 end) as HasPair
        from (select distinct a.role_id as aid, b.droit_id as droit_id
        from role a cross join droit b ) as allRD left outer join role_Droit RD
        on allRD.aid = RD.role_id and allRD.droit_id = RD.droit_id
        group by  allRD.droit_id,  allRD.aid
        order by  allRD.aid) AS matrix_view

我使用Postgres作为SGBD。请帮我搞结果2 !!! 请检查附图以显示表格和结果 enter image description here

1 个答案:

答案 0 :(得分:0)

尝试以下查询。 我只通过group by列扩展了您的查询。并将它们与sum合并。

select A.droit_id, sum(A."role A") as "role A", sum(A."role B") as "role B", sum(A."role C") as "role C", sum(A."role D") as "role D"
from (
    SELECT matrix_view.droit_id,
        case when matrix_view.aid = 1 then haspair end as  "role A" ,
        case when matrix_view.aid = 2 then haspair end as  "role B" ,
        case when matrix_view.aid = 3 then haspair end as  "role C" ,
        case when matrix_view.aid = 4 then haspair end as  "role D"

    from (
        SELECT allRD.aid as aid, allRD.droit_id, max(case when RD.role_id is not null then 1 else 0 end) as HasPair
            from (select distinct a.role_id as aid, b.droit_id as droit_id
            from role a cross join droit b ) as allRD left outer join role_Droit RD
            on allRD.aid = RD.role_id and allRD.droit_id = RD.droit_id
            group by  allRD.droit_id,  allRD.aid
            order by  allRD.aid
    ) AS matrix_view
) A
group by A.droit_id
order by A.droit_id

或者这个:

SELECT matrix_view.droit_id,
    sum(case when matrix_view.aid = 1 then haspair end) as  "role A" ,
    sum(case when matrix_view.aid = 2 then haspair end) as  "role B" ,
    sum(case when matrix_view.aid = 3 then haspair end) as  "role C" ,
    sum(case when matrix_view.aid = 4 then haspair end) as  "role D"

from (
        SELECT allRD.aid as aid, allRD.droit_id, max(case when RD.role_id is not null then 1 else 0 end) as HasPair
        from (
                select distinct a.role_id as aid, b.droit_id as droit_id
                from role a cross join droit b 
             ) as allRD 
        left outer join role_Droit RD
        on allRD.aid = RD.role_id and allRD.droit_id = RD.droit_id
        group by  allRD.droit_id,  allRD.aid
        order by  allRD.aid
    ) AS matrix_view
group by matrix_view.droit_id
order by matrix_view.droit_id