Below, is the schema of my brand_of_items table. For simplicity, shown here with two columns: id (primary and AI), symbol (varchar 50, unique)
Table - brand_of_items
id symbol
0 a
1 b
2 c
.. ..
10 j
Below, is the schema of my items_of_brand.
Table - mainIndexQuantity
id brand_of_items_id vol item_type salefinalizeddate
0 1 5 0 2005-5-11
1 1 6 0 2004-5-11
2 1 7 0 2011-5-11
3 1 8 0 2011-5-12
4 1 9 0 2011-5-12
5 1 10 0 2011-5-11
6 1 5 1 2012-5-11
7 1 6 1 2012-5-11
8 1 7 1 2011-5-11
9 1 8 1 2010-5-12
10 1 9 1 2012-5-12
11 1 10 1 2005-5-12
The mainIndexQuantity table brand_of_items_id columns is a foreign key which points to brand_of_items (id).
The mainIndexQuantity table item_type column is not a foreign key, which it should be.
The two item types are: 0 = retail and 1 = wholesale
I want to calculate the ratio of the types of items (retail vs wholesale) per each_brand_of_items table entry. The goal is to see if the a brands item is selling more in retail or wholesale.
**
Adding Complexity:
I want to add a date column to mainIndexQuantity table and want to find out the difference in sum of RetailVolume and WholesaleVolume and group the results by salefinalizeddate field.
This is to help determine what items in what seasons sold more and the (delta) difference in sum of RetailVolume & WholeSaleVolume will help to select items to pay most attention to.
Try this:
SQL Fiddle Demo.
This will give you:
Assuming that:
wholesaleRatiois the count of the items of type Whole sale to the count of all items.RetailRatiois the count of the items of typeretailto the count of all items.If this ration is for the total sum of the
volcolumn to the totalvolyou can do this instead:Note that:
LEFT JOIN, so that you got the unmatched rows in the result set, i.e, those brand items that has no entries theMainIndexQuantitytable. If you don’t want to include them, useINNER JOINinstead.1.0to get the count with decimal places, as noted by @JW.Update 1
To include the
Total Volume,Retail Volume SumandWholesale Volume sumtry this:Updated SQL Fiddle Demo.
This will give you:
If you want to sort the result set by these total and sums, put this query in a subquery, then you can do this:
But your last requirement is not clear, are you looking for those brand of items that has the highest of retio/wholesale ratis and volumns or select the highest values of them?
For the later one:
Update 2
To get those brands that has the highest total volume, you can do this:
Like this.
Note that:
This will give you the brands that has the highest total volume, if you are looking for those that has the highest ratio, you have to replace the having clause to get the max of the ratio rather than the max of total volume.
This will give you the items that have the highest total volume, so you might expect to have more than item, in case there was multiple items having the highest total volume, like in this updated fiddle demo. In this case, to get only one, you have to use
LIMITto return only one.