mysql - 返回重新洗牌数据,将字段值设置为新列

时间:2011-07-01 19:25:53

标签: mysql database

我怎么能改变这个

 SELECT 
    FieldA
    FieldB
    FieldC
  FROM mydata
  ORDER BY FieldA;


+------------------------------------------+-------------------+-----------------+
| FieldA                                   | FieldB            | FieldC          |
+------------------------------------------+-------------------+-----------------+
| 123                                      | cca               |              23 |
| 123                                      | dde               |              12 |
| 234                                      | cca               |              44 |
| 234                                      | dde               |              32 |
| 456                                      | dde               |              11 |
| 456                                      | cca               |              45 |

+------------------------------------------+-------------------+-----------------+

到此:

+------------------------------------------+-------------------+-----------------+
| FieldA                                   | cca               | dde             |
+------------------------------------------+-------------------+-----------------+
| 123                                      | 23                |              12 |
| 234                                      | 44                |              32 |
| 456                                      | 32                |              11 |
+------------------------------------------+-------------------+-----------------+

2 个答案:

答案 0 :(得分:2)

尝试这样的事情:

    SELECT 
    FieldA AS FieldA,
    SUM(IF(FieldB='cca', FieldC, 0)) AS cca,
    SUM(IF(FieldB='dde', FieldC, 0)) AS dde
    FROM mydata
    GROUP BY FieldA
    ORDER BY FieldA;

答案 1 :(得分:1)

你可以pivot the table from columns to rows使用MySQL(继续滚动几个例子)。 PHP中的解决方案将更快/更容易编写,但效率较低。