使用大小写对计算的列进行过滤和排序(未找到列)

时间:2019-05-21 08:18:49

标签: mysql sql

我正在尝试使用大小写对计算列进行过滤和排序,但出现语法错误。

  

未找到列差异和和列付款和

我需要能够拥有WHERE和ORDER BY子句。

我有两个表“合同”和“付款”。

合同

+----+-----------------+-----------+-----------+
| id | contract_number | legal_sum | bonus_sum |
+----+-----------------+-----------+-----------+
|  1 |    110258465651 |        50 |        20 |
|  2 |    564984656355 |        15 |        12 |
|  3 |    548498415165 |       150 |        35 |
+----+-----------------+-----------+-----------+

付款

+----+--------------+----------+
| id | contract_id  | paid_sum |
+----+--------------+----------+
|  1 | 564984656355 |        7 |
|  2 | 564984656355 |        1 |
|  3 | 564984656355 |        2 |
+----+--------------+----------+
  1. 首先,我需要计算合法总和与奖金总和之间的差(difference_sum)
  2. 然后我需要获取付款总额。paid_sum(payments_sum)
  3. 然后,如果(payments_sum-差额之和<= 0),我需要按条件进行排序

所以我进行了此查询,但它说difference_sum不存在:

SELECT
    (contracts.legal_sum - contracts.bonus_sum) as difference_sum
    sum(payments.paid_sum) as payments_sum,
    CASE
        WHEN (difference_sum - payments_sum) <= 0 THEN "All paid"
        WHEN (difference_sum - payments_sum) > 0 THEN "Not paid"
    END AS isPaid
FROM contracts
INNER JOIN payments on contracts.id = payments.contract_id
WHERE isPaid = "All paid"
ORDER BY isPaid

示例输出:

+----------------+--------------+----------+
| difference_sum | payments_sum |  isPaid  |
+----------------+--------------+----------+
|             30 |           30 | All paid |
|             48 |           15 | Not paid |
|            100 |          100 | All paid |
+----------------+--------------+----------+

1 个答案:

答案 0 :(得分:1)

尝试

SELECT difference_sum, payments_sum, isPaid 
FROM (
    SELECT  payments_sum,
        (contracts.legal_sum - contracts.bonus_sum) as difference_sum
        CASE
            WHEN (contracts.legal_sum - contracts.bonus_sum - payments_sum) <= 0 THEN "All paid"
            WHEN (contracts.legal_sum - contracts.bonus_sum - payments_sum) > 0 THEN "Not paid"
        END AS isPaid
    FROM contracts
    INNER JOIN ( 
       SELECT contract_id, sum(payments.paid_sum) as payments_sum
       FROM payments 
       GROUP BY contract_id
    ) payments on contracts.id = payments.contract_id
) q
WHERE isPaid = "All paid"
-- why order by a single value ?
-- ORDER BY isPaid 

可能还需要添加contract_id列以使其更加有用。