在MySQL中将多行转换为列

时间:2014-10-01 12:27:50

标签: mysql sql pivot

我有两张桌子:

表A

+-------+--------+
| Data  | Acc_No |
+-------+--------+
| Unix  |     10 |
| Linux |     20 |
+-------+--------+ 

表B

+-----+----------+--------+
| Obj | Type     | Amount |
+-----+----------+--------+
|  10 | rev      | 100.00 |
|  10 | revision | 200.00 |
+-----+----------+--------+

我想要像这样的输出

 +-------+--------+----------+--------+-----------+----------+
 | Data  | Acc_No | Type     | Amount | Type_1    | Amount_1 |
 +-------+--------+----------+--------+-----------+----------+
 | Unix  | 10     | rev      | 100    | revision  | 200      |
 +-------+--------+----------+--------+-----------+----------+

我尝试使用简单的连接来完成它。这是查询:

SELECT a.Data,a.Acc_No, b.Type, b.Amount, bb.Type AS "Type_1", bb.Amount AS "Amount_1"
FROM TableA a,TableB b, TableB bb
WHERE a.Acc_No = b.Obj AND
      b.Obj = bb.Obj AND
      bb.Obj = a.Acc_No AND
      a.Acc_No =10;

但我得到了这个输出。

+------+--------+----------+--------+----------+----------+
| Data | Acc_No | Type     | Amount | Type_1   | Amount_1 |
+------+--------+----------+--------+----------+----------+
| Unix |     10 | rev      | 100.00 | rev      |   100.00 |
| Unix |     10 | revision | 200.00 | rev      |   100.00 |
| Unix |     10 | rev      | 100.00 | revision |   200.00 |
| Unix |     10 | revision | 200.00 | revision |   200.00 |
+------+--------+----------+--------+----------+----------+

我试着在这个网站上搜索答案,我甚至用谷歌搜索了它,但我找不到合适的答案。

1 个答案:

答案 0 :(得分:5)

您当前的查询已关闭,但我建议对其进行一些小的更改以获得结果。如果您想使用JOIN“转动”数据,那么您需要在每个后续连接中区分要从TableB返回的值。

例如,当您想要返回type=rev时,您需要为该值包含特定的过滤器。然后你会用type=revision做同样的事情。我还建议您使用LEFT JOIN加入TableB,如果每个type都没有Acc_no个值,那么您仍会返回数据。

select
  a.data,
  a.acc_no,
  b.type,
  b.amount,
  bb.type as type_1,
  bb.amount as amount_1
from tablea a
left join tableb b
  on a.acc_no = b.obj
  and b.type = 'rev'
left join tableb bb
  on a.acc_no = bb.obj
  and bb.type = 'revision';

请参阅SQL Fiddle with Demo

您也可以使用某些条件聚合获得此结果,然后您不必多次加入TableB

select
  a.data,
  a.acc_no,
  max(case when b.type = 'rev' then b.type end) as type,
  max(case when b.type = 'rev' then b.Amount end) as Amount,
  max(case when b.type = 'revision' then b.type end) as type_1,
  max(case when b.type = 'revision' then b.Amount end) as Amount_1
from tablea a
left join tableb b
  on a.acc_no = b.obj
group by a.data, a.acc_no
order by a.acc_no;

请参阅SQL Fiddle with Demo