【问题标题】:Convert SQL table from Long Data to Wide Data将 SQL 表从长数据转换为宽数据
【发布时间】:2020-12-04 16:45:38
【问题描述】:

我有一个包含调查数据的 SQL 表。不幸的是,调查问题是长数据而不是宽数据(我有一个包含所有问题编号的列,我需要问题编号是它们自己的列)。

我有:

question_id | question_format_id | response----- | format_type | question
---63-------|------8-------------|--synchronous--|--likert-----|How will you attend class
---64-------|------3-------------|--COVID concern|short answer-|Reason for selection

我想要:

63 ----------------------| 64
8------------------------| 3
synchornous--------------| COVID concern
likert modality----------| short answer
How will you attend class| Reason for selection

这可能吗? 原因是我正在尝试对为问题 63 选择特定答案的学生进行报告。但是,一旦我对问题的回答进行过滤,我就不再看到这两个问题。

任何建议将不胜感激。

【问题讨论】:

  • 您使用的是哪种 DBMS 产品? “SQL”只是一种查询语言,而不是特定数据库产品的名称。请为您使用的数据库产品添加tagWhy should I tag my DBMS
  • 确实需要 unpivot,但 unpivoting 技术可能会从一个 DBMS 更改为另一个。那么,你的呢?因为SQL 只是一种查询语言。
  • 我正在使用 Microsoft SQL Server Management Studio。

标签: sql sql-server pivot unpivot


【解决方案1】:

首先是 UNPIVOT 子句,然后是 PIVOT 子句,例如

SELECT [1] AS col1, [2] AS col2
  FROM
  (
   SELECT *
     FROM ( SELECT CAST(question_id AS VARCHAR(MAX)) AS question_id, 
                   CAST(question_format_id AS VARCHAR(MAX)) AS question_format_id, 
                   response,format_type,question,
                   ROW_NUMBER() OVER (ORDER BY question_id) AS rn
              FROM [tab] ) t  
  UNPIVOT  
     (val FOR col IN   
        (question_id,question_format_id,response,format_type,question)  
     ) AS upt 
   ) ut
 PIVOT 
 (
  MAX(val) FOR rn IN ([1],[2]) 
 ) AS pt  

为了以垂直方式转置值。

Demo

【讨论】:

    猜你喜欢
    • 2020-08-11
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多