无法加入子查询

unable to join on a sub query

抱歉问题名称我不确定如何描述这个问题:

参加以下 CTE

WITH cte_form_answers AS (
SELECT fa.id
,      MAX(CASE WHEN fa.question = 'contact' THEN fa.answer END) AS ContactMethod
FROM formanswers fa
GROUP BY fa.id)

SELECT * FROM cte_form_answers 
id | ContactMethod
0  | Mobile
1  | Landline

及以下table

SELECT id, ContactMethod, Contact from contacts
id | ContactMethod | Contact
0  | Mobile        | xxxx-xxx-xxx
0  | Email         | xxx@email.com
1  | Landline      | xxxx-xxxx-xxx
1  | Mobile        | xxx-xxx-xxxx

我正在尝试使用我的 CTE 中的 contatMethod 加入联系人 table

我自己的尝试是:

WITH cte_form_answers AS (SELECT fa.id
,      MAX(CASE WHEN fa.question = 'contact' THEN fa.answer END) AS ContactMethod
FROM formanswers fa
LEFT JOIN contacts c 
ON   c.id = fa.id 
AND  c.ContactMethod = ( SELECT fa1.id, MAX(CASE WHEN fa1.question = 'contact' THEN fa1.answer END) 
                         FROM formanswers fa1 GROUP BY fa1.ID 
                         GROUP BY fa.id)

这会导致错误 SQL Error [42601]: ERROR: subquery must return only one column Position: 722

有人可以指导我如何正确执行此操作吗?

请注意,联系人 table 是一个缓慢变化的维度,因此它有一个 end_date 列,我也在连接中对其进行了过滤,但我认为这对这个问题没有影响。

您需要加入您正在聚合的另一个范围。例如:

WITH cte_form_answers AS (
    SELECT fa.id,
        MAX(fa.answer) FILTER(WHERE fa.question = 'contact') AS ContactMethod
    FROM formanswers fa
    GROUP BY fa.id
)
SELECT *
FROM cte_form_answers a
LEFT JOIN contacts c ON c.id = fa.id AND c.ContactMethod = a.ContactMethod

如果您愿意,也可以使用另一个 CTE:

WITH 
    cte_form_answers AS (
        SELECT fa.id,
            MAX(fa.answer) FILTER(WHERE fa.question = 'contact') AS ContactMethod
        FROM formanswers fa
        GROUP BY fa.id
    ),
    cte_form_contact AS (       
        SELECT *
        FROM cte_form_answers a
        LEFT JOIN contacts c ON c.id = fa.id AND c.ContactMethod = a.ContactMethod
    )
SELECT * FROM cte_form_contact