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