CREATE TABLE T1(client_id int, Loancount int, PRIMARY KEY (client_id));
INSERT INTO T1(client_id, Loancount)
SELECT DISTINCT C.client_id, count(loan_id) as LoanCount
FROM CLIENT as C, DISP as D, LOAN as L
WHERE (C.client_id=D.client_id) AND (D.account_id=L.account_id)
group by C.client_id;
CREATE TABLE T2 (client_id int, Trancount int, PRIMARY KEY (client_id));
INSERT INTO T2(client_id, Trancount)
(SELECT DISTINCT C.client_id, count(trans_id) as Trancount
FROM CLIENT as C, DISP as D, TRANSACTION as T
WHERE (C.client_id=D.client_id) AND (D.account_id=T.account_id)
group by C.client_id) ;
SELECT DISTINCT T1.client_id, IF(Trancount>=LoanCount,Trancount,LoanCount) as Maxcount
FROM T1,T2
WHERE T1.client_id=T2.client_id;
DROP Table T1;
DROP Table T2;
[当我尝试在此处运行此查询(https://www.eversql.com/sql-syntax-check-validator/)时,它说周围存在错误。插入T1。该代码虽然编译。
错误消息:“您的SQL语法有错误;似乎该错误在周围:'在第6行中,INSERT INTO T1(client_id,Loancount)SELECT DISTINCT C.client_id,count(lo')”
您是否一次将所有查询粘贴到查询检查器?它很可能一次只接受一个查询。
您可以对单个查询执行相同的操作。不需要表(在这种情况下,您应该使用临时表):
SELECT q.client_id, IF(max(q.Trancount)>=max(q.LoanCount),max(q.Trancount),max(q.LoanCount))
FROM (
SELECT C.client_id, 0 as LoanCount, count(T.trans_id) as Trancount
FROM CLIENT C,
JOIN DISP D ON D.client_id=C.client_id
JOIN TRANSACTION T ON T.account_id=D.account_id
group by C.client_id
UNION
SELECT C.client_id, count(L.loan_id) as LoanCount, 0 as Trancount
FROM CLIENT C,
JOIN DISP D ON D.client_id=C.client_id
JOIN LOAN as L ON L.account_id=D.account_id
group by C.client_id
) as q
group by Q.client_id