I have a table of sales belonging to various customers.
A customer can have more than one sale.
How do I figure out the nth sale for each customer/sale?
I am using Laravel but a plain MySQL answer would be just as good.
My query builder is:
$q = DB::table('sales AS S')
->select(DB::raw('CONCAT("row_", S.id) AS DT_RowId'),
'S.id', 'S.created_at', 'users.name AS agent',
DB::raw('CONCAT(C.first_name, " ", COALESCE(C.last_name, "")) AS name'), 'S.net',
DB::raw('(S.net - P.base_buy_price) AS margin'),
DB::raw('((S.net - P.base_buy_price)/P.base_price * 100) AS margin_percent'))
->join('users', 'users.id', '=', 'S.user_id')
->join('customers AS C', 'C.id', '=', 'S.customer_id')
->join('products AS P', 'P.id', '=', 'S.product_id')
->get();
Clarification
Lets say customer A has bought three times, on dates 2015-06-12, 2015-06-17 and 2016-01-17.
In the results I want each one of those rows telling me which sale is the nth i.e.:
2015-06-12 - 1st sale
2015-06-17 - 2nd sale
2016-01-17 - 3rd sale
...
DB::raw('(SELECT COUNT(*) FROM sales WHERE sales.created_at <= S.created_at AND sales.customer_id = C.id) AS nth')
...
Seems very inefficient?