基于对的数据透视表

时间:2017-11-30 21:34:37

标签: mysql

我有一个包含ID, A, A_potential, B, B_potential, ...列的表。有些列有值,有些则没有。如果A没有值,则A_potential也不具有值。我想只显示具有值的列,但也要将列彼此配对。然后循环它,如果它们有价值,它就会显示它们配对。

我想表达什么

<div class="item">
  <div class="current">30</div> <!--A Value-->
  <div class="potential">35</div> <!--A Potential-->
</div>

<div class="item">
  <div class="current">50</div> <!--C Value-->
  <div class="potential">75</div> <!--C Potential-->
</div>

CURRENT TABLE

ID | A  | A_potential | B  | B_potential
--------------------------------------
1  | 35 | 50          | 15 | 30
2  | 0  | 0           | 10 | 70

我希望看到什么表格来看待环状物

ID | Type | Current | Potential
--------------------------
 3 | A    |  35     | 50
 3 | D    |  50     | 75

1 个答案:

答案 0 :(得分:1)

对每对使用UNION个查询。

SELECT id, 'A' AS Type, A AS Current, A_Potential AS Potential
FROM yourTable
WHERE A != 0 OR A_Potential != 0
UNION ALL
SELECT id, 'B' AS Type, B AS Current, B_Potential AS Potential
FROM yourTable
WHERE B != 0 OR B_Potential != 0
UNION ALL
SELECT id, 'C' AS Type, C AS Current, C_Potential AS Potential
FROM yourTable
WHERE C != 0 OR C_Potential != 0
...