mysql - 带有字符串值的mysql数据透视表
问题描述
我有一个只有两列这样的表
mysql> select * from stuff_table;
+------+-------+
| name | stuff |
+------+-------+
| John | shoes |
| Jim | bag |
| Ely | book |
| Tom | bag |
| Will | shoes |
| Pitt | book |
| Dean | bag |
| Luke | bag |
+------+-------+
我尝试了很多我发现的解决方案
select distinct
max(case when stuff='shoes' then name else name is null) end as shoes,
max(case when stuff='bag' then name else name is null end) as bag,
max(case when stuff='book' then name else name is null end) as book
from stuff_table;
但我刚得到这个
+-------+------+------+
| shoes | bag | book |
+-------+------+------+
| Will | Tom | Pitt |
+-------+------+------+
相反,我想得到这个
+-------+------+------+
| shoes | bag | book |
+-------+------+------+
| John | Jim | Ely |
| Will | Tom | Pitt |
| NULL | Dean | NULL |
| NULL | Luke | NULL |
+-------+------+------+
我也尝试过 sum(case...) 或 if(case..) 或 group by,但它不起作用。是否有任何 mysql 查询来获得这样的表?请帮忙。谢谢你。
解决方案
根据mysql
您使用的版本,这是建立row_number
每个组的一种方法,然后conditional aggregation
按该行号分组:
select
rn,
max(case when stuff = 'bag' then name end) 'bag',
max(case when stuff = 'book' then name end) 'book',
max(case when stuff = 'shoes' then name end) 'shoes'
from (
select *, row_number() over (partition by stuff order by name) rn
from stuff_table
) t
group by rn
由于您使用的是旧版本的mysql
,因此您需要使用user-defined variables
来确定行号。然后其余的工作相同。这是一个例子:
select
rn,
max(case when stuff = 'bag' then name end) 'bag',
max(case when stuff = 'book' then name end) 'book',
max(case when stuff = 'shoes' then name end) 'shoes'
from (
select *,
( case stuff
when @curStuff
then @curRow := @curRow + 1
else @curRow := 1 and @curStuff := stuff
end
) + 1 AS rn
from stuff_table, (select @curRow := 0, @curStuff := '') r
order by stuff
) t
group by rn
推荐阅读
- java - set() 方法在 JavaFX 属性中不起作用
- angular - Firestore 仅返回最后一个文档
- c# - 如何使用 ServiceStack 将 json 反序列化为多个 DataContract 之一
- android - 如何启用不在视图中的 HorizontalScrollView 中的特定按钮
- spring-boot - 如何永远使用spring boot jar
- android - 通知嵌套适配器内更改的项目
- scala - Spark DeltaLake Upsert(合并)正在抛出“org.apache.spark.sql.AnalysisException”
- java - 根据其中一项将 ArrayList 类过滤到另一个类中
- c# - Newtonsoft - 如何使用从另一个类获取其值的变量设置 JsonProperty 名称
- c# - C#:使用 params 参数分配数组