【发布时间】:2018-06-22 14:28:45
【问题描述】:
我有一个像这样只有两列的表格
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 查询来获得这样的表?请帮忙。谢谢。
【问题讨论】:
-
您的示例表缺少一列,该列将说明每个数据点将映射到透视输出中的哪一行。翻译:没有足够的信息来回答这个问题。
-
这是一种在应用程序语言中更容易解决的问题,而不是 SQL。
标签: mysql sql pivot pivot-table aggregate