MySQL 行转列、列转行 (简)

行转列用group by+sum if,列转行用union all

例子:

1、列转行

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;

在这里插入图片描述
在这里插入图片描述

2、行转列

SELECT 
  product_id,
  SUM(IF(store = 'store1', price, NULL)) 'store1',
  SUM(IF(store = 'store2', price, NULL)) 'store2',
  SUM(IF(store = 'store3', price, NULL)) 'store3' 
FROM
  Products1 
GROUP BY product_id ;

猜你喜欢

转载自blog.csdn.net/weixin_43825761/article/details/126803779