【问题标题】:combine values from multiple rows into single将多行的值合并为单个
【发布时间】:2021-08-31 11:43:15
【问题描述】:

我有一张表格,其中存储了学生录取详细信息和录取日期。录取日期分为多行,我想将三行中的值合并为一行。

select * from table

student_name         student_value         student_answer
   Drake                 day                    28
   Drake                 month                  2
   Drake                 year                  2010
   Drake                city                  San Diego
   Drake                zip code                11235
   Josh                  day                    15
   Josh                  month                   5
   Josh                  year                  2012
   Josh                 city                  Sacramento
   Josh                 zip code                45876

期望的结果(new_column):

student_name         student_value         student_answer         new_column
   Drake                 day                   28                  9282010
   Drake                 month                 9                   9282010
   Drake                 year                 2010                 9282010
   Drake                city                 San Diego             San Diego
   Drake                zip code               11235                11235
   Josh                  day                   15                  11152012
   Josh                  month                 11                  11152012
   Josh                  year                  2012                11152012
   Josh                 city                  Sacramento           Sacramento
   Josh                 zip code                45876                45876

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    您可以使用条件窗口函数:

    select t.*,
           (case when student_value in ('day', 'month', 'year')
                 then max(student_answer) filter (where student_value = 'month') over (partition by student_name) ||
                      max(student_answer) filter (where student_value = 'day') over (partition by student_name) ||
                      max(student_answer) filter (where student_value = 'year') over (partition by student_name)
                 else student_answer
            end) as new_column         
    from t;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-15
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多