将联接 table 中的列添加到交叉表查询

Add columns from joined table to crosstab query

我试图找出一种方法来生成 SQL 查询,以在视图中使用,以生成类似 Excel 的父子关系格式。

我有以下 tables

id name lastname email accepted
1 A a -- true
2 B b -- true
3 C b -- true
4 D d -- true
访客
id name accepted id_person (foreign_key -> person.id)
1 AGuest1 true 1
2 BGuest1 true 2
3 BGuest2 true 2
4 CGuest1 true 3
5 CGuest2 false 3
6 CGuest3 false 3

一个人可以有多位客人陪同him/her。

我可以使用以下交叉表查询生成以下结果:

Person Name Guest 1 Name Guest 2 Name Guest 3 Name
A AGuest1 -- --
B BGuest1 BGuest2 --
C CGuest1 CGuest2 CGuest3
SELECT *
FROM CROSSTAB (
    'SELECT p.name, g.name, g.name
    FROM person p JOIN guest g
    ON p.id = g.id_person
    ORDER BY 1,2')
    AS ("Person Name" varchar(100), "Guest 1 Name" varchar(100),
    "Guest 2 Name" varchar(100), "Guest 3 Name" varchar(100));

但我还想将来自 table 的额外信息包含到交叉表查询中,再加上没有客人的人,因此它会给出以下结果:

Person Full Name Person Accepted Guest 1 Name Accepted Guest 2 Name Accepted Guest 3 Name Accepted
Aa true AGuest1 true -- -- -- --
Bb true BGuest1 true BGuest2 true -- --
Cc true CGuest1 true CGuest2 false CGuest3 false
Dd true -- -- -- -- -- --

任何正确方向的帮助或指示都会有所帮助,谢谢!

您可以先根据人员 ID 分组,为每个客人行分配一个行号。然后加入 Person table 并使用 CASE 语句获取与客人数量和接受值相关的每一列。为了删除空值,您可以使用 MAX 聚合函数对剩余列进行聚合和分组。

SELECT CONCAT(p.name, p.lastname) AS PersonFullName,
       p.accepted                 AS PersonAccepted,
       MAX(CASE WHEN g.rn = 1 THEN g.name 
                ELSE NULL END   ) AS Guest1Name,
       MAX(CASE WHEN g.rn = 1 THEN g.accepted 
                ELSE NULL END   ) AS Guest1Accepted,
       MAX(CASE WHEN g.rn = 2 THEN g.name 
                ELSE NULL END   ) AS Guest2Name,
       MAX(CASE WHEN g.rn = 2 THEN g.accepted 
                ELSE NULL END   ) AS Guest2Accepted,
       MAX(CASE WHEN g.rn = 3 THEN g.name 
                ELSE NULL END   ) AS Guest3Name,
       MAX(CASE WHEN g.rn = 3 THEN g.accepted 
                ELSE NULL END   ) AS Guest3Accepted
FROM       Person p
LEFT JOIN  (SELECT *, ROW_NUMBER() OVER(PARTITION BY id_person
                                        ORDER     BY id) AS rn
            FROM Guest                                      )g
        ON p.id = g.id_person
GROUP BY PersonFullName, 
         PersonAccepted
ORDER BY PersonFullName

试试看 here.