使用SQL案例的结果进行比较并返回另一个案例

时间:2019-07-14 17:42:13

标签: sql sql-server

我正在尝试通过使用返回此比较结果的情况来比较返回金额的总和的结果:

case UPDATECURRENTFORUM:
      return Object.assign({}, state, {
        currentForum: action.payload,
      });

每当我回叫quantity_sent时,都会得到一个“无效的列名quantity_sent”。我还有其他方法可以使用此新创建的列上的结果在案例内进行比较吗?

2 个答案:

答案 0 :(得分:1)

尝试一下-

SELECT 
u.name, u.account,
SUM (
    CASE u.account
        WHEN t.sent_to THEN t.quantity * -1
        ELSE t.quantity 
    END
) AS quantity_sent,
CASE 
    WHEN SUM (
        CASE u.account
            WHEN t.sent_to then t.quantity * -1
            ELSE t.quantity 
        END ) > u.available THEN 'YES'
        ELSE 'NO' 
END as analysis_result
FROM users as u 
INNER JOIN trans as t
ON u.account in (t.sent_to, t.received_by)
GROUP BY u.name, u.account;

答案 1 :(得分:1)

您需要重复该表达式或使用子查询:

select name, account, quantity_sent,
       (case when quantity_sent > u.available then 'YES'
             else 'NO'
        end) as analysis_result
from (select u.name, u.account,
             sum(case u.account
                     when t.sent_to then t.quantity * -1
                     else t.quantity
                 end) as quantity_sent
      from users u inner join
           trans t
           on u.account in (t.sent_to, t.received_by)
      group by u.name, u.account
     ) u;

这是SQL通用规则的一部分,您不能在定义它的SELECT中重用列别名。原因很简单:SQL不保证SELECT中表达式的求值顺序。

相关问题