我有这个数据
| 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
在 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);
在 MySQL 中进行交叉表的一种方法是使用子选择:
select car_name,
(select price from t t2 where t2.car_name = t1.car_name and year = 2011) as '2011',
(select price from t t2 where t2.car_name = t1.car_name and year = 2012) as '2012'
from t t1
group by car_name
如果您每年每辆车有多个记录,那么 sum(price)。