如何根据where子句将单个列拆分为两个

时间:2014-06-19 07:35:01

标签: postgresql

有人可以建议我如何将一个列分成两列吗?这是我的名为ax_cash_book的表。

Please find the image of the table below

我想将金额列拆分为两个名为“Credit”的列,其中trans_type ='Credit'和“Debit”,其中trans_type ='Debit'。我试着写一个这样的查询:

select amount as Credit, amount as Debit from ax_cash_book

但我无法找到包含where子句的合适位置。请提出一些问题来解决问题。

提前谢谢!!

1 个答案:

答案 0 :(得分:5)

您可以使用CASE ... WHEN语句:

SELECT
    CASE WHEN trans_type = 'Credit' THEN amount ELSE 0 END AS Credit,
    CASE WHEN trans_type = 'Debit' THEN amount ELSE 0 END AS Debit
FROM ax_cash_book

当trans_type列等于“Credit”时,它将使用金额数据库字段。

我认为如果该值是一个信用,则没有借方,因此ELSE 0

这同样适用于借方字段。