如何在比较sql中同一个表中的两列时进行选择

时间:2016-08-10 20:05:40

标签: mysql sql sql-server

CREATE VIEW mainT 
AS SELECT transactionId AS accountId, glbalance AS debit 
IF(totalDebit > totalCredit), glbalance as Credit IF(totalCredit > totalDebit) 
FROM `trialbalanceView`

是否可以在SQL中生成此类查询?请任何帮助,我们将不胜感激。

2 个答案:

答案 0 :(得分:0)

你想要一个CASE陈述......

CREATE VIEW mainT 
AS 
SELECT 
    transactionId AS accountId, 
    glbalance AS debit,
    case when totalDebit > totalCredit then glbalance else null end as Debit,
    case when totalCredit > totalDebit then glbalance else null end as Credit
FROM trialbalanceView

答案 1 :(得分:0)

我相信你所寻找的东西类似于下面的东西。我假设您的问题与基于逻辑操作的条件列值有关。如果该假设不正确,请提供更多详细信息,说明需要通过示例和基表数据解决的问题究竟是什么。

CREATE VIEW mainT 
AS 
SELECT transactionId AS accountId, 
    CASE WHEN totalDebit > totalCredit
        THEN glbalance 
    ELSE null AS debit, 
    CASE WHEN totalDebit < totalCredit
        THEN glbalance 
    ELSE null AS credit
FROM trialbalanceView

谢谢, ķ