Mysql
 sql >> Database >  >> RDS >> Mysql

Utilizzo di due valori aggregati da una sottoquery SELECT in una singola query SELECT esterna

Puoi unire le 2 sottoquery in 1:

SELECT MAX(c.cust_id) AS max_nh_cust_id,
       MAX(a.avail_balance) AS max_nh_avail_balance 
FROM account a INNER JOIN customer c 
ON a.cust_id = c.cust_id 
WHERE c.state = 'NH'

e unisciti in questo modo:

SELECT a.cust_id
FROM account a 
INNER JOIN customer c ON a.cust_id = c.cust_id
INNER JOIN (
  SELECT MAX(c.cust_id) AS max_nh_cust_id,
         MAX(a.avail_balance) AS max_nh_avail_balance 
  FROM account a INNER JOIN customer c 
  ON a.cust_id = c.cust_id 
  WHERE c.state = 'NH'
) t ON c.cust_id > t.max_nh_cust_id AND a.avail_balance > t.max_nh_avail_balance
WHERE c.state = 'MA'

Vedi la demo .
Risultati:

> | cust_id |
> | ------: |
> |      13 |