postgresql 如何在SQL中不使用PIVOT函数进行透视?

bfhwhh0e  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(2)|浏览(149)

我想在不使用任何PIVOT函数的情况下透视一个表,而只使用纯SQL(例如PostgreSQL语法)。
以这个数据集为例:

Order |   Element | Value |
---------------------------
1     | Item      | Bread |
1     | Quantity  |  3    |
1     | TotalCost |  3,30 |
2     | Item      | Pizza |
2     | Quantity  |  2    |
2     | TotalCost |  10   |
3     | Item      | Pasta |
3     | Quantity  |  5    |
3     | TotalCost |  2,50 |

字符串
我希望以Order列为中心,并有一些类似的东西:

Order | Item | Quantity | TotalCost |
-------------------------------------
1     | Bread |    3    |    3,30   |
2     | Pizza |    2    |    10     |
3     | Pasta |    5    |    2,50   |


我该如何实现这一点呢,再说一次,不使用任何pivot函数?

ep6jt1vc

ep6jt1vc1#

溶液A

使用CASE WHEN语句:

SELECT Order, 
       MAX(CASE WHEN Element = 'Item' THEN Value END) AS Item, 
       MAX(CASE WHEN Element = 'Quantity' THEN Value END) AS Quantity, 
       MAX(CASE WHEN Element = 'TotalCost' THEN Value END) AS TotalCost
FROM MyTable
GROUP BY 1

字符串

溶液B

使用selfLEFT JOIN s:

SELECT A.Order, A.Item, B.Quantity, C.TotalCost
FROM
    (SELECT Order, Value as Item
    FROM MyTable
    WHERE Element = 'Item') as A
    LEFT JOIN
    (SELECT Order, Value as Quantity
    FROM MyTable
    WHERE Element = 'Quantity') as B ON A.Order = B.Order
    LEFT JOIN
    (SELECT Order, Value as TotalCost
    FROM MyTable
    WHERE Element = 'TotalCost') as C ON B.Order = C.Order


后者可能没有那么高效,但也有可能有用的用例。

tzcvj98z

tzcvj98z2#

在Postgres中,你可以使用FILTER

SELECT Order, 
       MAX(Value) FILTER (WHERE Element = 'Item') AS Item, 
       MAX(Value) FILTER (WHERE Element = 'Quantity') AS Quantity, 
       MAX(Value) FILTER (WHERE Element = 'TotalCost') AS TotalCost
FROM MyTable
GROUP BY 1;

字符串
请注意,ORDER是一个SQL关键字,所以它是一个糟糕的列名选择。

相关问题