具有 INT 和 NVARCHAR 数据类型的多列的 SQL Pivot [重复]

Posted

技术标签:

【中文标题】具有 INT 和 NVARCHAR 数据类型的多列的 SQL Pivot [重复]【英文标题】:SQL Pivot on multiple columns with INT and NVARCHAR datatypes [duplicate] 【发布时间】: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) 请向我们展示您的尝试。 【参考方案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

【讨论】:

以上是关于具有 INT 和 NVARCHAR 数据类型的多列的 SQL Pivot [重复]的主要内容,如果未能解决你的问题,请参考以下文章

将 nvarchar 值转换为数据类型 int 和其他 SQL Server 错误时失败

nvarchar 值转换为数据类型为 int 发生语法错误

将数据类型 int 转换为 nvarchar 时出错

将数据类型 NVarchar 转换为 int 时出错

SQL 异常:将 nvarchar 值“[anyvalue]”转换为数据类型 int 时转换失败

在 SQL Server 2008 中将 NVARCHAR 转换为 INT 数据类型