Proper ORDER BY query for items based on associated items in the same table
I want to rank a list of bundled products (each bundle is a singular item
in the table) that is based on the aggregate number of its individual
components (which are each singular items in the same table) sold.
So I have a table of products that contain both a main item and its
associated components in the same table. There is a column that identifies
it as a main item or component (main='1' or main='0') as well as a column
that associates components to the main item's row ID (master_id='xxx'). I
also have a column that keeps track of how many are sold (column is called
sold_count).
But how do I sort the resulting query of the main items by the total
number of sold_count of the all the associated components of each main
item?
SELECT Item_Name FROM 'products' WHERE main='1' ORDER BY _______________ ???
Here is the table structure:
ID | Item_Name | Main | Master_ID | Sold_Count
1 Kit A 1 0 0
2 Widget A1 0 1 3
3 Widget A2 0 1 6
4 Kit B 1 0 0
5 Widget B1 0 4 2
6 Widget B2 0 4 8
So I would want to have Kit A and Kit B sorted based on the number of the
associated widgets sold. So the sort should be:
Kit B
Kit A
Because Kit B had 10 widget components sold, while Kit A only had 9 total.
No comments:
Post a Comment