如何在MySql中转动查询

时间:2013-10-23 12:57:36

标签: mysql sql pivot

我有下表:

Year, Name, Revenue, Qty 

我想要一个

的结果表
  

名称,2012财年收入,2012财年,2013财年,2013财年

如何在Sql for MySql中做?

由于

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

如果你正在使用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>";

或任何适合您需求的东西。