我有下表:
Year, Name, Revenue, Qty
我想要一个结果表
名称、2012 年收入、2012 年数量、2013 年收入、2013 年数量
如何在 Sql for MySql 中执行?
谢谢
MySQL 没有 PIVOT 函数,但您可以使用带有 CASE 表达式的聚合函数获得结果:
select name,
sum(case when year = 2012 then revenue else 0 end) revenue2012,
sum(case when year = 2012 then qty else 0 end) qty2012,
sum(case when year = 2013 then revenue else 0 end) revenue2013,
sum(case when year = 2013 then qty else 0 end) qty2013
from yourtable
group by name
如果您使用的是 php,则可以根据需要显示它:
$table=mysqli_query($con,"
SELECT *
FROM table
");
echo "<table>
<tr>
<th>Name</th>
<th>Revenue2012</th>
<th>Qty2012</th>
<th>Revenue2013</th>
<th>Qty2013</th>
</tr>";
while($row = mysqli_fetch_array($table))
{
echo "<tr>";
echo "<td>". $row['Name'] . "</td>";
echo "<td>". $row['Revenue'] . $row['Year'] . "</td>";
echo "<td>". $row['Qty '] . "</td>";
echo "<td>". $row['Revenue'] . $row['Year'] . "</td>";
echo "<td>". $row['Qty '] . "</td>";
echo "</tr>";
}
echo "</table>";
或者任何适合您的需求。