0
select id, s
from (
         select o_user_id as id, sum(total_price) as s
         from Orders o
         group by o.o_user_id
     ) as t1
where s = (select max(t1.s) from t1)

it returns a bug said table t1 doesn't exist.

I want to find the id of the user who spends the most money among all of the orders

here is the table of order enter image description here

2 Answers 2

4

That alias is out of scope for the subquery

select id, s
from (
         select o_user_id as id, sum(total_price) as s
         from Orders o
         group by o.o_user_id
     ) as t1
where s = (select max(t1.s) from t1)

You can do

WITH T1 AS 
    (
      select o_user_id as id, sum(total_price) as s
         from Orders o
         group by o.o_user_id
     ) 
SELECT id, s
  FROM T1
 WHERE s = (select max(t1.s) from t1);
Sign up to request clarification or add additional context in comments.

Comments

0

If you want only one row, you can use order by and limit:

select o_user_id as id, sum(total_price) as s
from Orders o
group by o.o_user_id
order by s desc
limit 1;

In MySQL 8+, you can use window functions. To get multiple rows in the event of ties, use rank():

select ou.*
from (select o_user_id as id, sum(total_price) as s,
             rank() over (order by sum(total_price) desc) as seqnum
      from Orders o
      group by o.o_user_id
     ) ou
where seqnum = 1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.