I have an SQL final exam in college in a few days and I have a query that’s driving me crazy! I know it’s a dumb query, but I’m just getting started and can’t figure it out.
So, there’s basicaly 2 tables, Client and Orders.
Client Orders
--------- ---------
PK Client_Id PK Order_Id
Name Client_Id FK
Order_Total
Date
Now, they ask me to "List the name of the client that bought the most in 2011"
So, for what I thought, this requires on one side, that I SUM all the Order_Total and Group by Client from 2011, then from that table, select the client with the MAX() sum of order totals, and then show only the name of that client. The problem is that I can’t figure how to put all that in one query.
Hope somebody can help!
Thank you all for your very quick responses! I’m really impressed!
Now, I don’t mean to be picky or anything, but just in case my teacher doesn’t accept the "Limit" or "Select top" statement, is there any way to do this query without those?
Edit: Original code attempt ported from comments:
SELECT
C.NAME
FROM
CLIENTS C,
ORDERS O
WHERE
O.CLIENT_ID = C.CLIENT_ID
AND O.DATE BETWEEN '1/1/2011 00:00:00.000' and '12/31/2011 23:59:59.999'
HAVING SUM(O.ORDER_TOTAL) >= ALL (SELECT SUM (O2.ORDER_TOTAL) FROM ORDER O2 GROUP BY O2.CLIENT_ID)
1 Answer