【SQL】行列转换

列转行

将一个表的列转为行在这里插入图片描述
1、先将product_id,store1 的值取出来,其中store1 的列名改为 price
其中新增了一列store,第一行值为store1

SELECT product_id, 'store1' store, store1  price FROM products WHERE store1 IS NOT NULL

在这里插入图片描述
2、依次类推,将store2、store3的也查询出来;

SELECT product_id,'store2' store,store2 price From products where store2 is not null;

在这里插入图片描述

SELECT product_id,'store3' store,store3 price From products where store3 is not null;

在这里插入图片描述
3、最后将三次查询结果取并集,采用union all(union all和union区别,后者对数据取并集并且去重和排序,union all直接取并集)

select product_id,'store1' store,store1 price From products where store1 is not null
union all
SELECT product_id,'store2' store,store2 price From products where store2 is not null
union all
SELECT product_id,'store3' store,store3 price From products where store3 is not null;

最后转换结果显示为:
在这里插入图片描述

行转列

先通过查询创建表

CREATE TABLE product_changed (
  product_id INT,
  store VARCHAR(10),
  price DECIMAL(10, 2)
)
SELECT product_id, 'store1' AS store, store1 AS price FROM products WHERE store1 IS NOT NULL
UNION ALL
SELECT product_id, 'store2' AS store, store2 AS price FROM products WHERE store2 IS NOT NULL
UNION ALL
SELECT product_id, 'store3' AS store, store3 AS price FROM products WHERE store3 IS NOT NULL;

1、通过group by 将product_id 进行分组结合聚合函数+IF 将数据写入列中

select product_id,
SUM(if(store = 'store1',price,null)) AS 'store1',
SUM(if(store = 'store2',price,null)) AS 'store2',
SUM(if(store = 'store3',price,null)) AS 'store3'
from product_changed
group by product_id;

在这里插入图片描述
2、或者通过case when的语法

select product_id,
SUM(case when store = 'store1' THEN price else null end) AS 'store1',
SUM(case when store = 'store2' THEN price else null end) AS 'store2',
SUM(case when store = 'store3' THEN price else null end) AS 'store3'
from product_changed
group by product_id;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值