使用mysql select结果生成二维坐标

lmvvr0a8  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(210)

我对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

而原始表中的数据是什么并没有确定。我要怎么做?

uoifb46i

uoifb46i1#

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

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。

相关问题