Limiting Query Results for Multiple Categories

Discussion in 'Programming' started by paulostrom, Dec 25, 2007.

  1. #1
    Suppose I have a table with the fields "location", daily_sales", and "date". There are 3 different locations and I want the Top 3 "daily_sales" for each location.

    I know this can easily be done using separate queries for each location (i.e., Select Top 3 Daily_Sales from Sales where location = "A" Order By Daily_Sales DESC). Unfortunately, there are actually thousands of "locations" in my database and using separate queries doesn't seem to be very scalable.

    I've made various attempts using grouping, query of queries, and nested queries but can't seem to get the results I need. This seems like a simple enough problem and I'm hoping there is a simple solution that I am just overlooking. Any suggestions would be greatly appreciated.
     
    paulostrom, Dec 25, 2007 IP
  2. paulostrom

    paulostrom Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Problem solved. Someone pointed me in the right direction. Below is the query that produces what I needed.

    select location
         , Daily_Sales
      from Sales as T
     where ( select count(*) 
               from Sales  
              where location
                = T.location
                and Daily_Sales 
                > T.Daily_Sales ) < 3
    order
        by location
         , Daily_Sales desc
    Code (markup):
     
    paulostrom, Dec 26, 2007 IP