1

行转列,值转换成列

 

 

1. 值转换成列操作。值转列操作:[1777题库]

 

表:Products

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| store       | enum    |
| price       | int     |
+-------------+---------+
在 SQL 中,(product_id,store) 是这个表的主键。
store 字段是枚举类型,它的取值为以下三种 ('store1', 'store2', 'store3') 。
price 是该商品在这家商店中的价格。
 

找出每种产品在各个商店中的价格。

可以以 任何顺序 输出结果。

返回结果格式如下例所示。

 

示例 1:

输入:
Products 表:
+-------------+--------+-------+
| product_id  | store  | price |
+-------------+--------+-------+
| 0           | store1 | 95    |
| 0           | store3 | 105   |
| 0           | store2 | 100   |
| 1           | store1 | 70    |
| 1           | store3 | 80    |
+-------------+--------+-------+
输出:
+-------------+--------+--------+--------+
| product_id  | store1 | store2 | store3 |
+-------------+--------+--------+--------+
| 0           | 95     | 100    | 105    |
| 1           | 70     | null   | 80     |
+-------------+--------+--------+--------+
解释:
产品 0 的价格在商店 195 ,商店 2100 ,商店 3105 。
产品 1 的价格在商店 170 ,商店 3 的产品 1 价格为 80 ,但在商店 2 中没有销售。
View Code
====方法1======
SELECT 
product_id  ,
min( case when store = 'store1' then price else null end ) store1,
min( case when store = 'store2' then price else null end ) store2,
min( case when store = 'store3' then price else null end ) store3
  
FROM Products 
group by product_id


====方法2=====
 
 SELECT 
product_id  ,
nullif( sum( case when store = 'store1' then price else 0 end ) ,0) store1,
nullif( sum( case when store = 'store2' then price else 0 end ) ,0) store2,
nullif( sum( case when store = 'store3' then price else 0 end ) ,0) store3
  
 FROM Products 
 group by product_id

===
体会如上两种方法, 结果是一样的。 其实就是 null 和0 的关系,最终为0 的结果让展示为null,这个地方是重点。

 

posted @ 2024-09-02 20:27  萌哥-爱学习  阅读(0)  评论(0编辑  收藏  举报