如何 select 来自不同列的多个整数数据并将它们合并到数组整数的单列中

How to select multiple Integer data from different columns and merge them into single column of array integer

我的 POSTGRES 数据库中有如下 table

Table name:userDetails

column 1: userId (Bigint)

column 2: questionId1 (int) Foreign key:: userQuestions(id)

column 3: answer1 (String)

column 4: questionId2 (int) Foreign key:: userQuestions(id)    |

column 5: answer2 (String) 

Table 姓名:userQuestions

column 1: id(bigint)

column 2: question(String)

我想select根据userId输出如下,

column 1: userId (Bigint)

column 2: questionId's (int [])(questionId1 and questionId2)

column 3: questions (String [])( array of questions from table userQuestions against the the questionId1 and questionId2 )

column 4: answer(String []) (answer1 and answer2 from userDetails table in array of String)

请帮我写sql查询。

样本数据

Table名称::用户详细信息

|userId         |questionId1        |answer1        |questionId2        |answer2

  abc                 1               "hp"                2               "tommy"

Table姓名::用户问题

id          question 

1           "What is brand name of your laptop?"

2           "What is name of your pet?"

预期输出::

userId          questionIds        answers                       questions

 abcd              [1,2]        ["hp","tommy"]              ["What is brand 
                                                              name of your 
                                                              laptop?",
                                                            "What is name of 
                                                             your pet?"]

我认为唯一的方法是将输出插入临时 table,这样你就可以插入 questionId1 及其问题字符串和 answer1,然后插入 questionId2 与它的问题字符串和 answer2 到相同的列,然后显示结果。

编辑: 正如您在此处请求的那样,这是一个在 SQL 服务器中运行的示例(我不知道 POSTGRES,从未使用过它)

Select t1.userId, t1.questionId1 as questionId, (Select t2.question from userQuestions t2 where t2.id = t1.questionId1) as questions, answer1 as answer into #TempTable from userDetails
UNION ALL Select t1.userId, t1.questionId2 as questionId, (Select t2.question from userQuestions t2 where t2.id = t1.questionId2) as questions, answer2 as answer into #TempTable from userDetails
Select * from #TempTable

不要忘记在重新执行代码之前,您必须使用 Drop table #TempTable

删除临时 table

我在 SQL Server 2016 上尝试了一个类似的代码,它工作得很好。

我会换一种说法

select d.userid, d.questionid1 || ',' || d.questionid2, d.answer1 || ' ' || d.answer2, 
        string_agg(q.question,',')
from userDetails d
join userQuestions q on q.id = d.questionid1 or q.id = d.questionid2
GROUP BY d.userid