我有這個數據交叉表在MySQL
| car_name | year | price
| Honda | 2011 | 123
| Honda | 2012 | 124
| Suzuki | 2011 | 1234
| Suzuki | 2012 | 1235
IM要去如何變成
| car_name | 2011 | 2012 |
| Honda | 123 | 124
| Suzuki | 1234 | 1235
這個請大家幫我
我有這個數據交叉表在MySQL
| car_name | year | price
| Honda | 2011 | 123
| Honda | 2012 | 124
| Suzuki | 2011 | 1234
| Suzuki | 2012 | 1235
IM要去如何變成
| 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
更簡潔的版本:「選擇car_name, MAX(如果(年= '2011',價格,0))作爲'2011', MAX(如果(年=「2012 ',price,0))as'2012' from t GROUP BY car_name「 – ErichBSchulz
在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
如果每車每年,那麼總和多個記錄(價錢)。
你可以使用PHP或其他語言來創建查詢,或者它都在MySQL做? –
其實我需要的都在MySQL做 – softboxkid