You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PostgreSQL表按交易类型拆分并新增type列?

解决方案

你可以通过**LATERAL JOIN结合VALUES子句**实现行拆分与类型列生成,同时调整对应金额列的取值,完整SQL如下:

SELECT
  CASE t.type
    WHEN 'sale' THEN c."saleAmount"
    ELSE 0
  END AS "saleAmount",
  CASE t.type
    WHEN 'buy' THEN c."buyAmount"
    ELSE COALESCE(c."buyAmount", NULL)
  END AS "buyAmount",
  o."id",
  t.type
FROM
  "Charges" c
LEFT JOIN "Operations" o ON o."id" = c."operationsId"
LATERAL (
  VALUES
    ('sale') WHERE c."saleAmount" > 0,
    ('buy') WHERE c."buyAmount" > 0
) t(type)
ORDER BY
  o."id", t.type;

语句说明:

  1. 行拆分逻辑:LATERAL JOIN配合VALUES子句,针对每一行原数据生成对应类型的记录:

    • 当saleAmount > 0时,生成type='sale'的行
    • 当buyAmount > 0时,生成type='buy'的行
    • 若两者都大于0,则自动拆分为两行,满足需求
  2. 金额列调整:

    • 标记为sale的行,保留原saleAmount,buyAmount设为0(原buyAmount为NULL时则保留NULL)
    • 标记为buy的行,保留原buyAmount,saleAmount设为0
  3. 排序:按Operations.id和type排序,确保结果顺序与目标表一致

执行结果:

saleAmountbuyAmountidtype
200NULLid1sale
3000id2sale
0500id2buy
0100id3buy

内容的提问来源于stack exchange,提问作者AmphaWolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:50:31