tags:

views:

29

answers:

1

I have a single table called orders. It has 3 fields I care about: price, type, and bid. Bid is an int with either 0 or 1 depending on if the order is to buy or sell something. 1 is buy, 0 is sell.

orders

|typeID  |price |bid|
|1       |10    |0|
|2       |20    |0|
|3       |30    |0|
|4       |50    |0|
|1       |80    |0|
|2       |30    |0|
|3       |50    |0|
|4       |10    |0|
|1       |8     |1|
|2       |7     |1|
|3       |9     |1|

I'm trying to find which 100 distinct types have the largest difference between the average price of buy and sell orders.

I'm not sure how to go about doing this. I know I can order by an average price for either buy or sell orders, but I need to order by the difference between them. I'm using mysql if that matters.

A: 

I'm fairly confident that this should work:

SELECT `typeID`, AVG(IF(`bid`, `price`, 0)) AS `average_buy_price`, AVG(IF(`bid`, 0, `price`)) AS `average_sell_price`,
AVG(IF(`bid`, `price`, 0)) - AVG(IF(`bid`, 0, `price`)) AS `difference`
FROM `orders`
GROUP BY `typeID`
LIMIT 100
ORDER BY `difference` DESC;
TehShrike