私はこのデータを持っています
| car_name | year | price
| Honda | 2011 | 123
| Honda | 2012 | 124
| Suzuki | 2011 | 1234
| Suzuki | 2012 | 1235
これをどう変えるか
| car_name | 2011 | 2012 |
| Honda | 123 | 124
| Suzuki | 1234 | 1235
私を助けてください
MySQL では、次のことができます。
SELECT car_name,
max(case when year = '2011' then price ELSE 0 END) as `2011`,
max(case when year = '2012' then price ELSE 0 END) as `2012`
FROM t
GROUP BY car_name
デモで SQL Fiddle を参照してください
PHPでは、ここにあなたの答えがあります:
$sql = "SELECT DISTINCT `year` FROM `table`";
$result = mysql_query($sql);
$sql2_select = "SELECT t1.`car_name`";
$sql2_from = "FROM `table` t1";
$i = 2;
while($row = mysql_fetch_row($result)) {
$year = $row[0];
$sql2_select .= ", t{$i}.`price` AS `$year`"
$sql_from .= " LEFT JOIN (SELECT `car_name`, `price` WHERE `year` = '$year') AS t{$i}";
$sql_from .= " ON t1.`car_name` = t2.`car_name`";
$i++;
}
$sql2 = $sql2_select . ' ' . $sql2_from . ' ' . "GROUP BY t1.car_name";
$result = mysql_query($sql2);