mysql中的交叉表

mysql中的交叉表,mysql,crosstab,Mysql,Crosstab,我有这些数据 | 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 请用PHP帮助我,以下是您的答案: $sql = "S

我有这些数据

| 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

请用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,
  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

请参见

在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)。

你可以使用PHP或其他语言来创建查询,还是所有的查询都必须在MySQL中完成?事实上,我需要所有的查询都必须在MySQL更简洁的版本中完成:“选择车名,max(If(year='2011',price,0))作为
2011
,max(If(year='2012',price,0))作为2012年的
t集团的