【问题标题】:transposing mysql temporary table rows to columns将mysql临时表行转置为列
【发布时间】:2015-05-15 22:23:47
【问题描述】:

我想转置这张表

一个 |乙| C ---------------- 1 | 10 | “XXX” 1 | 20 | “年年” 2 | 40 | “XXX” 2 | 50 | “年年” 3 | 10 | “XXX” 3 | 20 | “年年” 3 | 60 | “ZZZ”

到这里:

一个 | XXX |年年 | ZZZ | ---------------------- 1 | 10 | 20 | 0 | 2 | 40 | 50 | 0 | 3 | 10 | 20 | 60 |

我只能使用临时表,并且我在帮助中读到自引用不起作用。 https://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html 有什么帮助吗?

【问题讨论】:

  • 这称为旋转。如果你知道你想要的列,谷歌“mysql pivoting”。如果列基于列中的值,则谷歌“mysql 动态透视”。

标签: mysql


【解决方案1】:

如果您知道column C 中的值,则可以使用条件聚合:

select A, 
       coalesce(max(case when c = 'XXX' then B end),0) XXX,
       coalesce(max(case when c = 'YYY' then B end),0) YYY,
       coalesce(max(case when c = 'ZZZ' then B end),0) ZZZ
from yourtable
group by A

Fiddle

如果不是并且您不知道潜在列的数量,那么您需要使用dynamic sql

【讨论】:

  • 我尝试了你的建议,但我得到的结果是每行只有 1 个值。
  • @sievy -- 你复习过小提琴吗?给定您的样本输入,它会产生您想要的结果。
  • 你是对的。我检查了它,它工作正常。谢谢
猜你喜欢
  • 1970-01-01
  • 2020-11-18
  • 1970-01-01
  • 2021-05-16
  • 2012-03-29
  • 1970-01-01
  • 2015-02-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多