我在Postgres中有这个查询:
Select
"Charges"."saleAmount", "Charges"."buyAmount", "Operations"."id"
From
"Charges"
Left Join
"Operations" On "Operations"."id" = "Charges"."operationsId"
Order By
"Operations"."id"
| 销售额|购买金额|身份证|
| - ------|- ------|- ------|
| 二百|零|识别码1|
| 三百|五百|身份2|
| 无|一百|id3|
我需要改变它:根据saleAmount
〉0或buyAmount
〉0添加一个新列type
,当saleAmount
和buyAmount
位于同一行时,将其分为两行。
| 销售额|购买金额|身份证|类型|
| - ------|- ------|- ------|- ------|
| 二百|零|识别码1|销售|
| 三百|无|身份2|销售|
| 无|五百|身份2|买|
| 无|一百|id3|买|
如何将表格转换为这种格式?
色谱柱type
可由以下物质制成:
(CASE
WHEN "saleAmount" > 0 THEN 'sale'
WHEN "buyAmount" > 0 THEN 'buy'
END) as "type"
4条答案
按热度按时间relj7zay1#
您可以使用
UNION ALL
从一行创建两行。例如:顺便说一下,Operations表的连接似乎是多余的。Charges有一个operationsId,然后它链接到具有相同ID的Operations行,或者它没有operationsId,然后它不链接到Operations行。那么,为什么不显示“Charges”.“operationsId”,而不是连接到Operations表来显示相同的ID呢?
vs3odd8k2#
您可以联接到 values 表构造函数,并使用case表达式确定有多少行符合联接条件:
yyhrrdl83#
我想你可以用union all。
lyr7nygr4#
在Postgres中,可以使用
values
和一个横向连接将两列反透视到行,然后在where
子句中过滤掉不需要的行:原始查询中
left join
的用途并不明显,所以我将其放在一边--但是如果需要,您可以很容易地将其添加到查询中。