如何从不同的列中选择多个Integer数据并将其合并到数组整数

时间:2018-08-01 09:21:43

标签: sql postgresql postgresql-9.3

我的POSTGRES数据库中有如下表

表名: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) 

表名:userQuestions

column 1: id(bigint)

column 2: question(String)

我想根据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查询。

样本数据

表名:: userDetails

|userId         |questionId1        |answer1        |questionId2        |answer2

  abc                 1               "hp"                2               "tommy"

表名::用户问题

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?"]

2 个答案:

答案 0 :(得分:1)

我认为唯一的方法是将输出插入临时表中,这样您可以将questionId1和它的问题字符串和answer1插入,然后将questionId2和它的问题字符串一起插入和answer2放在同一列中,然后显示结果。

编辑: 正如您所要求的,这里是一个可以在SQL Server中工作的示例(我不知道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删除临时表

我已经在SQL Server 2016上尝试过类似的代码,并且工作正常。

答案 1 :(得分:1)

我会换个说法

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