views:

54

answers:

1

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 greatest to least?

Is there a way to get this all done in one query?

+4  A: 

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.

Nick Fortescue
+1 Looks like it's exactly what he needs.
gbianchi
very nice. I will give this a try. For future reference, how did you highlight the syntax in the SQL statement?
Derek Adair
@Derek: Just highlight the text and click on the code (101010) icon.
Alix Axel
Hmm... I did the code Icon. How did you get the blue text to appear?and it looks perfect except I'm going to add SUM(Sale) to the select and ORDER BY SUM(Sale)
Derek Adair
I've just edited to reformat your code a bit in your question
Nick Fortescue
exactly what i'm talking about Nick. How do i do that?
Derek Adair
@Derek thanks. I've edited the answer to add the Sum(Sale) to it. If this works for you it is polite to accept the answer as correct by clicking the check mark to the side of the answer
Nick Fortescue
@Nick: that makes two of us editing at the same time :)
Jonathan Leffler
Will do!I'm implementing it right now
Derek Adair
Works as expected. Although the dudes who have this DB formated haven't really done all that great of a job... so implementation isn't going all that smooth... hahaha
Derek Adair
@Nick: You can alias the SUM columns, and reference the alias in the ORDER BY...
OMG Ponies