2015-05-15 29 views
1

我想转此表移调MySQL的临时表行

 
A | B | C 
---------------- 
1 | 10 | "XXX" 
1 | 20 | "YYY" 
2 | 40 | "XXX" 
2 | 50 | "YYY" 
3 | 10 | "XXX" 
3 | 20 | "YYY" 
3 | 60 | "ZZZ" 

此列:

 
A | XXX | YYY | 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 任何帮助?

+2

这被称为pivoting。如果你知道你想要的列,Google“mysql pivoting”。如果列是基于列中的值,那么Google将使用“mysql dynamic pivoting”。 –

回答

0

如果你知道在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

+0

我尝试了你的建议,但我得到了每行只有1个值的结果。 – sievy

+0

@sievy - 你看过小提琴吗?鉴于您的样本输入,它会产生您想要的结果。 – user2480596

+0

你说得对。我检查了它,它工作正常。谢谢 – sievy