Mysql查询重新格式化

时间:2015-11-16 22:56:47

标签: mysql

我有一个表格以下列和数据:

Company     | Cash    | Acctrec   | Acctpay 
Comp1__     | 123     | 123       | 123  
Comp2__     | 123     | 123       | 123  
Comp3__     | 123     | 123       | 123  
Comp4__     | 123     | 123       | 123

我想提供如下数据:

Company     | Account | Amount
Comp1__     | Cash    | 123       
Comp1__     | Acctrec | 123        
Comp1__     | Acctpay | 123
Comp2__     | Cash    | 123       
Comp2__     | Acctrec | 123        
Comp2__     | Acctpay | 123
Comp3__     | Cash    | 123       
Comp3__     | Acctrec | 123        
Comp3__     | Acctpay | 123
Comp4__     | Cash    | 123       
Comp4__     | Acctrec | 123        
Comp4__     | Acctpay | 123           

有很多公司。如何制定查询以返回这样的数据?谢谢!

1 个答案:

答案 0 :(得分:3)

使用UNION组合每个检索其中一列的查询。

SELECT Company, 'Cash' AS Account, Cash AS Amount
FROM YourTable
UNION
SELECT Company, 'Acctrec' AS Account, Acctrec AS Amount
FROM YourTable
UNION
SELECT Company, 'Acctpay' AS Account, Acctpay AS Amount
FROM YourTable