mysql - reshuffling data returned, set field value as new column
How could I transform this
SELECT
FieldA
FieldB
FieldC
FROM mydata
ORDER BY FieldA;
+------------------------------------------+-------------------+-----------------+
| FieldA | FieldB | FieldC |
+------------------------------------------+-------------------+-----------------+
| 123 | cca | 23 |
| 123 开发者_Python百科 | dde | 12 |
| 234 | cca | 44 |
| 234 | dde | 32 |
| 456 | dde | 11 |
| 456 | cca | 45 |
+------------------------------------------+-------------------+-----------------+
to this:
+------------------------------------------+-------------------+-----------------+
| FieldA | cca | dde |
+------------------------------------------+-------------------+-----------------+
| 123 | 23 | 12 |
| 234 | 44 | 32 |
| 456 | 32 | 11 |
+------------------------------------------+-------------------+-----------------+
Try something like this:
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;
You can pivot the table from columns to rows using MySQL (keep scrolling for several examples). A solution in PHP will be quicker/easier to write but less efficient.
精彩评论