Skip to content
Advertisement

Generate query using 5 tables

I’ve created my table. I’m trying to craate a query that multiply and add sold_quantity from sold table and sale_price from on_sale table and called it R1 for now, and retail_price from product table and sold_quantity from sold table called it R2 for now.

In my query, I want to calculate my revenue. The catch is there’s two different date but one sale quantity. That means it’s kinda hard for me to distinguish twO types of sales( discounted sale, retail sale).

For example, on Feb.1st, I have a sale going on, I sold 10 quantity, and price sold is as sale_price and date is saved as sale_date, refer to On_sale table. On Feb.2, I sold 8 quantity , but price sold is saved as retail_price and saved as sold_date.

This is what I want:

SAMPLE DATA:

Store table:

Sold Table:

On_sale Table:

Product Table:

City table:

EXPEXTED RESULT:

Explanation of my data

This is very confusing. First I need to display year based on sold date and sale date, then calculate revenue. For example,in year 2018, the revneue is (2 from on_sale table’s sale_price) + (12 (3 * 4, 3 is the sold_quantity from sold_table, and 4 is retail_price) = 14.

The city size is separated by ranges, where 0>#<100 is small 100>=x<200 is medium and anything above 200 is large. the city name in the parenthesis is just to help track. The city is based on the city name and state in store table, and that is doen by comparing store_number on both sold table and store table

This requires me to join city table after querying to get R1(normal price) and R2(on sale price). Here’s what I got. I’m very lost:

Advertisement

Answer

Here is an approach that might get the job done. The logic is to use aggregate subqueries to do the intermediate computations.

This query gets the revenue from the On_sale table by year.

This other query gets the revenue per store and per year, using tables Sold and Product:

Now we can JOIN the results of these queries with the City and Store tables. At the same time, we can split the cities into different size categories and use that to aggregate the results. I am using LEFT JOIN in case one of the subqueries produces an empty resultset (else, INNER JOIN is ok):

This demo on DB Fiddle with your sample data demonstrates the intermediate steps, and finally returns:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement