1
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;

When I try running this query here(https://www.eversql.com/sql-syntax-check-validator/), it says an error exists around. INSERT INTO T1. The code compiles though.

Error Message:"You have an error in your SQL syntax; it seems the error is around: 'INSERT INTO T1(client_id, Loancount) SELECT DISTINCT C.client_id, count(lo' at line 6"

1 Answers1

2

Are you pasting all the queries at once to the query checker? Most likely it accepts only one query at the time.

You can do the same with single query. No need for tables:

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

Btw, you should use temporary tables in cases where you just create table and then drop it after a query.

slaakso
  • 8,331
  • 2
  • 16
  • 27