What am I doing wrong in Postgresql, trying to find stores that sell the top 10% of profitable items

38 Views Asked by At

I am working with a database of liquor sales in Iowa. I have a sales table with all transactions from the year, and a stores table which I JOINed because I wanted to see the names of the stores and not just their store codes.

On the sales table, I found the top-selling 10% of items by the sum of total profit generated in the state, and now I am trying to figure out what stores sold these items, and how much they sold.

-The inner query is the instructions for finding those top 10% of items (I'm a newbie and didn't know how to do this in SQL, but when in Excel found that the top 10% of items by total profit ended with an item that produced $62,765 in profit. So I did >= 62765). The inner query showed me the 385 items in this top 10%.

-I made it a table to JOIN with my outer query. In my outer query I ask for the stores that sell these items:

SELECT sales.store, stores.name, SUM(sales.total) AS total 
FROM stores INNER JOIN sales
            USING(store)
   INNER JOIN (SELECT item, description, store
                FROM sales
                GROUP BY item, description, store
                HAVING SUM((btl_price-state_btl_cost)*bottle_qty) :: numeric >= 62765) AS top_10_pct
        ON sales.store = top_10_pct.store
GROUP BY sales.store, stores.name
ORDER BY total DESC

I think this is wrong because when I run it, it only gives me 9 rows. This isn't right, I know more than 9 stores sell these top items -- there are 1352 distinct stores on the sales table, and 385 items.

But I can’t figure out what I am doing wrong! Thank you for any ideas you have for a SQL novice!

0

There are 0 best solutions below