mysql - 使用mysql select结果制作二维坐标

标签 mysql sql

我对 mysql 查询有疑问。

我有一个表,其中包含以下数据。

From To Weight
--------------
A    B    1
A    C    3
B    C    2
D    E    4

我想得到像下面这样的sql结果..

(?) A   B   C   D   E
----------------------
A   0   1   3   0   0
B   0   0   2   0   0
C   0   0   0   0   0 
D   0   0   0   0   4
E   0   0   0   0   0

并且原始表中的数据是什么还不确定。 我怎样才能做到这一点?

最佳答案

如果您知道原始列,您可以执行以下操作:

select c.col1,
       sum(case when to = 'A' then weight else 0 end) as a,
       sum(case when to = 'B' then weight else 0 end) as b,
       sum(case when to = 'C' then weight else 0 end) as c,
       sum(case when to = 'D' then weight else 0 end) as d,
       sum(case when to = 'E' then weight else 0 end) as d
from (select 'A' as col1 union all select 'B' union all select 'C' union all select 'D' union all select 'E'
     ) c left join
     t
     on t.from = c.col1
group by c.col1;

如果您不知道原始列,您可以将这些值组合成一个字符串:

select col1.col, 
       group_concat(col2.col, ':', t.weight order by col2.col)
from ((select `from` as col from t
      ) union   -- on purpose to remove duplicates
      (select `to` from t
      )
     ) col1 cross join
     ((select `from` as col from t
      ) union   -- on purpose to remove duplicates
      (select `to` from t
      )
     ) col2 left join
     t
     on col1.col = t.`from` and col2.col = t.`from`
group by col1.col;

如果您确实想要单独的列并且不知道其值,那么您将需要动态 SQL。

关于mysql - 使用mysql select结果制作二维坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53248359/

相关文章:

php - 在结果集中实例化对象......最佳实践?

mysql - 基于多对多关系进行选择的SQL查询

php - 在 MySQL 中使用 LIKE 子句优化表以进行搜索

mysql - 如何在 MySQL 数据库中的单个列索引的空间中索引多个列

mysql - 优化 MySQL 查询时出现问题

php - 选择像 A% 没有结果但 %A 有 php 的地方

mysql - 如何优化此 MySQL 查询以更快地执行?

python - 从游标创建临时表

java - 按代码排序

php - 在PHP中,如何实现和Java中StringTokenizer一样的目的?