SQL行到列值

时间:2015-07-15 04:23:27

标签: sql postgresql pivot rows

我有一个场景,购买我可以用现金,卡或代金券支付以上三种。但我需要一份报告,以单独的行显示所有付款类型,但我在一行中捕获了所有这些价值。问题是如何将行值传输到列中。

对于前。

╔═════════════════════════════════════════════════════╗
║ Order           Amount     Cash     Card    Voucher ║
╠═════════════════════════════════════════════════════╣
║ Purchase1       1000       500      300     200     ║
╚═════════════════════════════════════════════════════╝

但我需要结果

╔══════════════════════════════════╗
║ Order           Amount  PayType  ║
╠══════════════════════════════════╣
║ Purchase1        500     Cash    ║
║ Purchase1        300     Card    ║
║ Purchase1        200     Voucher ║
╚══════════════════════════════════╝

我们可以提供您完成上述格式的建议。

3 个答案:

答案 0 :(得分:0)

我建议你像这样使用UNION ALL

SELECT Order, Cash As Amount, 'Cash' As PayType
UNION ALL
SELECT Order, Card, 'Card'
UNION ALL
SELECT Order, Voucher, 'Voucher'

答案 1 :(得分:0)

一种取消表格的方法

SELECT "Order", 
       CASE WHEN n = 1 THEN Cash
            WHEN n = 2 THEN Card 
            WHEN n = 3 THEN Voucher END Amount,
       CASE WHEN n = 1 THEN 'Cash' 
            WHEN n = 2 THEN 'Card'
            WHEN n = 3 THEN 'Voucher' END PayType      
  FROM table1 CROSS JOIN generate_series(1, 3) n

输出:

|     Order | amount | paytype |
|-----------|--------|---------|
| Purchase1 |    500 |    Cash |
| Purchase1 |    300 |    Card |
| Purchase1 |    200 | Voucher |

这是 this stackoverflow question 演示

答案 2 :(得分:0)

在PostgreSQL数组函数中使用unnest

SELECT "Order",
        unnest(array[cash, card, voucher]) AS "amount",
        unnest(array['cash', 'card', 'voucher']) AS "PayType"
FROM bar
ORDER BY "PayType"

sqlfiddle