accounts
表包含 account_id
、account_type
、date_opened
。
loans
表包含 account_id
、balance
。
选择新贷款数量:
select count(a.account_id) from account a
where a.date_opened > LAST_DAY(now() - INTERVAL 1 MONTH)
and a.account_type = 'L'
选择未结贷款的数量:
select count(*) from loans l
where l.balance > 0
或
SUM(CASE WHEN l.balance > 0 THEN 1 ELSE 0 END) as loans_opened
如何在单个选择中执行此操作?我尝试过的事情:
select
count(a.account_id),
SUM(CASE WHEN l.balance > 0 THEN 1 ELSE 0 END) as loans_opened
from account a as new_loans,
LEFT JOIN loans l ON l.account_id = a.account_id
where a.date_opened > LAST_DAY(now() - INTERVAL 1 MONTH) and a.account_type = 'L'
退回 0 笔贷款
select
count(a.account_id) as new_loans,
count(l.account_id) as loans_opened
from account a as new_loans,
LEFT JOIN loans l ON l.account_id IN (SELECT account_id from account) and balance > 0
where a.date_opened > LAST_DAY(now() - INTERVAL 1 MONTH) and a.account_type = 'L'
查询永远不会返回
有没有办法在有或没有连接的情况下做到这一点?
最佳答案
您可以通过使用两个 SELECT
查询作为主查询的 SELECT
列表中的子查询来实现此目的:
SELECT (SELECT COUNT(*)
FROM account
WHERE date_opened > LAST_DAY(NOW() - INTERVAL 1 MONTH)
AND account_type = 'L') AS new_loans,
(SELECT COUNT(*)
FROM loans
WHERE balance > 0) AS open_loans;
关于MYSQL:从多个表返回多个计数而不加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53961374/