将订单数据中的产品从多个记录返回到列

时间:2019-07-11 15:56:54

标签: sql sql-server

我有一个SQL Server数据库,其中包含调查数据,并且非常接近此问题How to return ordered data from multiple records into one record in MySQL?

数据几乎相同。从上述问题中再次复制,但添加了毫秒和datetime2列。

SURVEY_TAKER_ID | QUESTION_NUMBER | RESPONSE
----------------+-----------------+-----------
101               1                 Apple
102               1                 Orange
103               1                 Banana
101               2                 Morning
102               2                 Evening
103               2                 Afternoon
101               3                 Red
102               3                 Blue
103               3                 Yellow

我正在尝试使用按功能分组,但不是将响应分组,而是以行格式显示响应。

select 
    s.survey_taker_ID, AVG(s.Millisecond)Duration, 
    (case when s.Question_Number = 1 then s.Answer end Product1,
    (case when s.Question_Number = 2 then s.Answer end Product2
from 
    survey as s
group by 
    s.survey_taker_ID,  s.Question_Number,s.Answer

输出:

Survey_Taker_ID | Duration | Product1  | Product2 
----------------+----------+-----------+----------
    101         |  11125   | Apple     | Morning
    102         |  12545   | Orange    | Evening 

遗憾的是,我之前已经做过,但现在似乎无法实现。我知道我犯了一些愚蠢的错误。任何示例代码都会有所帮助。

1 个答案:

答案 0 :(得分:0)

我认为您想要汇总:

select s.survey_taker_ID, AVG(s.Millisecond) as Duration, 
       max(case when s.Question_Number = 1 then s.Answer end) as Product1,
       max(case when s.Question_Number = 2 then s.Answer end) as Product2
from survey as s
group by s.survey_taker_ID;