Query result organization
I am trying to figure out the most efficient way to format this query.
I have three tables - Transaction, Purchase and Item.
The desired result is to select sales data (quantity/sales total) for each item for a specific client.
the tables are formatted as follows: (=primary key)*
Transaction: Transaction_ID*, Timestamp
Purchase: Purchase_ID*, Sale, Item_ID, Transaction_ID, Quantity
Item: Item_ID*, Client_ID, Description
As of right now I have a query set up to select each item for a given client_id:
SELECT Item_ID, Description FROM Item WHERE Client_ID = $ClientId
Then I store the results in an array, and executing a query to retrieve the sales data for each Item_ID between a given date-range:
SELECT Sale, Quantity
FROM Purchase INNER JOIN Transaction
ON Purchase.Transaction_ID = Transaction.Transaction_ID
WHERE Transaction.Timestamp >= $start
AND Transaction.Timestamp<= $end
Then for each row fetched, I sum the quantity.
It gets the job done, but is probably not the most efficient way to get this done.
I would like to order this data by the sales totals, putting the greatest number first
How would you go about sorting this from greates开发者_JAVA百科t to least?Is there a way to get this all done in one query?
would the following work?
SELECT Item_ID, SUM(Quantity), Sum(Sale)
FROM Item
JOIN Purchase ON Item.Item_ID=Purchase.Item_ID
JOIN Transaction ON Purchase.Transaction_ID=Transaction.Transaction_ID
WHERE Client_ID = $ClientId
AND Transaction.Timestamp>= $start
AND Transaction.Timestamp <= $end
GROUP BY Item_ID
ORDER BY SUM(Quantity), SUM(Sale) DESC
I think this is what you want from the good question you asked. There's probably a stupid mistake in there somewhere as I haven't tested it on your tables, but it ought to get you started.
精彩评论