Разница в количестве двух виртуальных столбцов - PullRequest
1 голос
/ 09 января 2020

Я хочу получить разницу между двумя столбцами, вот мой текущий запрос:

select customer_id as customers_id, sum(amount) as manual_amount,
       (select amount from customers where id = customers_id) as current_wallet_amount
FROM wallet_transactions 
where customer_id = 14438 
group by wallet_transactions.customer_id

Результат, который я получаю, прикреплен ниже:

enter image description here

Что мне нужно, так это разница между количеством в ручном режиме и current_wallet_amount. Любая помощь будет весьма заметна

Ответы [ 3 ]

2 голосов
/ 09 января 2020

Вы можете попробовать ниже -

With cte as
(
    select customer_id as customers_id, sum(amount) as manual_amount,
    (select amount from customers where id = customers_id) as current_wallet_amount,
    FROM wallet_transactions 
    where customer_id = 14438 
    group by wallet_transactions.customer_id
)

select  customers_id,manual_amount,current_wallet_amount,
manual_amount-current_wallet_amount as difference
from cte
1 голос
/ 09 января 2020
SELECT
  wt.customer_id AS customers_id, 
  SUM(wt.amount) AS manual_amount, 
  ANY_VALUE(customers.amount) AS current_wallet_amount,
  (SUM(wt.amount) - ANY_VALUE(customers.amount)) AS diff_amount
FROM wallet_transactions AS wt
JOIN customers ON customers.id = wt.customer_id
WHERE customer_id = 14438 
GROUP BY wt.customer_id
0 голосов
/ 09 января 2020
SELECT cu.id AS customers_id, 
       SUM(wt.amount) AS manual_amount, 
       cu.amount AS current_wallet_amount,
       SUM(wt.amount) - cu.amount AS difference
FROM wallet_transactions AS wt
JOIN customers cu ON cu.id = wt.customer_id
WHERE cu.id = 14438 
GROUP BY cu.id, cu.amount
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...