【问题标题】:SQL Pivot on multiple columns with INT and NVARCHAR datatypes [duplicate]具有 INT 和 NVARCHAR 数据类型的多列的 SQL Pivot [重复]
【发布时间】:2021-01-26 21:28:18
【问题描述】:

具有多列的 SQL Pivots 的新手。我想让表 1 看起来像表 2,以主题的多列 (teach_last, overall_mark, overall_pct) 为中心。任何建议表示赞赏。

表 1

表 2

【问题讨论】:

  • MS SQL Server 18
  • 您可以查看this
  • 1) 请不要使用图片,使用格式化文本。 2) 请向我们展示您的尝试。

标签: sql sql-server pivot


【解决方案1】:

您可以使用条件聚合:

select student_id,
       max(case when subject = 'Math' then teach_last end) as math_teach_last,
       max(case when subject = 'Math' then overall_mark end) as math_overall_mark,
       max(case when subject = 'Math' then overall_pc end) as math_overall_pct,
       max(case when subject = 'Science' then teach_last end) as science_teach_last,
       max(case when subject = 'Science' then overall_mark end) as science_overall_mark,
       max(case when subject = 'Science' then overall_pc end) as science_overall_pct,
       . . .
from t
group by student_id;

【讨论】:

    【解决方案2】:

    您还可以使用嵌套选择来透视表而不进行聚合:

    select distinct student_id,
        (select teach_last from students s1 where subject = 'Math' and s.student_id = s1.student_id) as [Math_teacher_last],
        (select overall_mark from students s1 where subject = 'Math' and s.student_id = s1.student_id) as [Math_overall_mark],
        (select overall_pct from students s1 where subject = 'Math' and s.student_id = s1.student_id) as [Math_overall_pct],
        (select teach_last from students s1 where subject = 'Science' and s.student_id = s1.student_id) as [Science_teacher_last],
        (select overall_mark from students s1 where subject = 'Science' and s.student_id = s1.student_id) as [Science_overall_mark],
        (select overall_pct from students s1 where subject = 'Science' and s.student_id = s1.student_id) as [Science_overall_pct],
        ...    
        from students s
    

    【讨论】:

      猜你喜欢
      • 2013-08-31
      • 2011-03-15
      • 2014-03-05
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      相关资源
      最近更新 更多