简体   繁体   English

Pivot 数据转换成字段和值

[英]Pivot data into field and values

I am having a table consisting of multiples rows and columns.我有一个由多行和多列组成的表。 I need to pivot down this table into 2 column consisting of field and values.我需要将此表中的 pivot 分成由字段和值组成的 2 列。

for Example my Input table is:例如我的输入表是:

Name Class Subject
Sam   2     Math
John  3    Science
Amy   4     Music

output Required: output 需要:

Field  Values
Name   Sam
       John
       Amy
Class   2
        3
        4
Subject Math
        Science
        Music

I tried everything but nothing works for me.我尝试了一切,但对我没有任何作用。 I am looking for solution in excel, Tableau or SQL.我正在 excel、Tableau 或 SQL 中寻找解决方案。 Anything works for me.任何事情都对我有用。 It would be great if you help me with the logic.如果你能帮助我理解逻辑,那就太好了。 Thank you in advance先感谢您

In SQL this is done with UNION在 SQL 中,这是使用UNION完成的

SELECT 'Name' AS Field, Name AS Values ORDER BY Class
UNION ALL
SELECT 'Class' AS Field, Class AS Values ORDER BY Class
UNION ALL
SELECT 'Subject' AS Field, Subject AS Values ORDER BY Class

If there are more columns, just continue the pattern.如果有更多列,则继续该模式。

ORDER BY Class assumes that Class is a unique key of the table, to ensure that each subquery is ordered consistently. ORDER BY Class假设Class是表的唯一键,以确保每个子查询的顺序一致。 If this isn't true, replace that with the actual primary key.如果不是这样,请将其替换为实际的主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM