Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

MS Access 2007 - query problem

  • 01-12-2010 03:41AM
    #1
    Registered Users, Registered Users 2 Posts: 109 ✭✭


    Hi, I'm quite new to Databases in general and SQL so I'm not exactly sure how to handle this query I've made.

    My code is as follows:
    [SIZE=1]SELECT CUST_NAME, MAX(AMOUNT) AS TOTAL_PURCHASES, YEAR
    
    FROM (
              SELECT C.CUST_NAME AS CUST_NAME, SUM(O.QUANTITY) AS QUANTITY,
                         SUM(B.PRICE*O.QUANTITY) AS AMOUNT, YEAR(O.DATE) AS YEAR
    
              FROM CUSTOMERS AS C, ORDERS AS O, BOOKS AS B
    
              WHERE C.CUST_ID = O.CUSTOMER_ID AND O.BOOK_ID = B.ISBN
    
              GROUP BY YEAR(O.DATE), C.CUST_NAME
         )
    
    GROUP BY CUST_NAME, YEAR
    
    ORDER BY YEAR;[/SIZE]
    
    
    What I want to do is end up with a table with three rows and three columns. The columns shall be CUST_NAME, TOTAL_PURCHASES, YEAR. The idea of the query is to obtain the three highest paying customers per year. By excluding the CUST_NAME in the first SELECT and the last GROUP BY I can get the top three purchases per customer per year but that leaves me without the company's name which is what I need.

    I appreciate any help anyone can provide on this.
    Thanks.


Comments

  • Registered Users, Registered Users 2 Posts: 646 ✭✭✭akamossie


    looking into the code, it looks fine, as i have not seen anything mentioned about company's name.
    its a little confusing here, like you have three columns and rows whhere you have three attributes, is the company name in another table, are your trying to join them together??

    I am a little rusty with DB haven't used in years, but what i see you are missing to join a table assuming there is one for company's name!!


  • Registered Users, Registered Users 2 Posts: 109 ✭✭Barti


    Sorry, I realised only now that I said company name rather than customer name. What I want to end up with is the customer name and the amount they purchased per year.

    I mixed up company and customer because my database is based on me being a warehouse and other companies buying from me, so are therefore my customers.

    By only doing the inner SELECT I get the following output table:

    firstselect.png

    So now I was just wondering how to get from that down to only the top purchaser for each year?


Advertisement