I am trying to fetch a hierarchical data in my database. Here is my initial code.
        SELECT TOP 5
            year, location_state, location_city,
            COUNT(tf.customer_key) Number_of_Customers
        FROM TransactionFact tf
        JOIN LocationDim as ld
            ON ld.location_key = tf.seller_location_key
        JOIN DateDim dd
            ON dd.date_key = tf.order_date_key
        WHERE dd.year = 2016 and location_state = 'SP'
        GROUP BY dd.year, ld.location_state, ld.location_city
        ORDER BY dd.year DESC, Number_of_Customers DESC
And here is the result, result.
Basically, in the query, what I want to do is to not hard code the location_state in the WHERE clause. I want to make it dynamic so that what I get are the top 5 cities in each state.
Here are the column names for the LocationDim table
location_key
location_zip_code_prefix
location_state
location_city
EDITED: What I need is something like this.
+------+----------------+---------------+---------------------+
| year | location_state | location_city | Number_of_Customers |
+------+----------------+---------------+---------------------+
| 2016 |    STATE_1     |    city_1     |       100           |
+------+----------------+---------------+---------------------+
| 2016 |    STATE_1     |    city_2     |       90            |
+------+----------------+---------------+---------------------+
| 2016 |    STATE_1     |    city_3     |       89            |
+------+----------------+---------------+---------------------+
| 2016 |    STATE_1     |    city_4     |       88            |
+------+----------------+---------------+---------------------+
| 2016 |    STATE_1     |    city_5     |       20            |
+------+----------------+---------------+---------------------+
| 2016 |    STATE_2     |    city_1     |       100           |
+------+----------------+---------------+---------------------+
| 2016 |    STATE_2     |    city_2     |       45            |
+------+----------------+---------------+---------------------+
| 2016 |    STATE_2     |    city_3     |       23            |
+------+----------------+---------------+---------------------+
| 2016 |    STATE_2     |    city_4     |       10            |
+------+----------------+---------------+---------------------+
| 2016 |    STATE_2     |    city_5     |       5             |
+------+----------------+---------------+---------------------+
PS: Sorry, this is my first question in stackoverflow. If this question is duplicated, pls drop the link and I'll give it a go. Thank u in advance.
 
     
     
     
    