[英]Convert Row Data into Single Column w/ Key Column
I would like to convert row data into a single column with a key column from the original row data using SQL or R.我想使用 SQL 或 R 将行数据转换为带有来自原始行数据的键列的单列。
Example Row:示例行:
---------------------------------------------------------------------
| Customer # | Item1 | Item2 | Item3 | Item4 |
---------------------------------------------------------------------
| 1111111 | A12345 | C45567 | G34589 | A34529 |
---------------------------------------------------------------------
This is my desired result:这是我想要的结果:
-------------------------------
| Customer # | Columnname | Value |
-------------------------------
| 1111111 | Item1 | A12345 |
| 1111111 | Item2 | C45567 |
| 1111111 | Item3 | G34589 |
| 1111111 | Item4 | A34529 |
You want to unpivot the columns of your table to rows.您想将表的列反透视为行。
You tagged the question mysqli
, so let me assume that you are using MySQL.您标记了问题
mysqli
,所以让我假设您正在使用 MySQL。 In this database, you can use union all
:在这个数据库中,你可以使用
union all
:
select customer, 'Item1' columname, Item1 value from mytable
union all select customer, 'Item2', Item2 from mytable
union all select customer, 'Item3', Item3 from mytable
union all select customer, 'Item4', Item4 from mytable
Other databases have neater solutions, typically using a lateral join and values()
.其他数据库有更简洁的解决方案,通常使用横向连接和
values()
。 In Postgres for example:以 Postgres 为例:
select t.customer, x.columname, x.value
from mytable t
cross join lateral (values
('Item1', Item1), ('Item2', Item2), ('Item3', Item3), ('Item4', Item4)
) x(columname, value)
In SQL Server, you would just replace cross join lateral
with cross apply
.在 SQL Server 中,您只需将
cross join lateral
替换为cross apply
。
In R, you can use dplyr and tidyr as follows.在 R 中,您可以按如下方式使用 dplyr 和 tidyr。
library(dplyr)
library(tidyr)
data <- tibble(customer = c(11111),
item1 = c('sfdhdshv'),
item2 = c('dfh'),
item3 = c('kjg'))
data
# customer item1 item2 item3
# <dbl> <chr> <chr> <chr>
# 1 11111 sfdhdshv dfh kjg
data %>%
pivot_longer(!customer, names_to = 'columnname', values_to = 'value')
# customer columnname value
# <dbl> <chr> <chr>
# 1 11111 item1 sfdhdshv
# 2 11111 item2 dfh
# 3 11111 item3 kjg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.