I have three tables
table 1: items (int,itemName)
table 2: orders(order id,oDate)
table 3: orderDetails(orderId, itemId, itemQnt)
Here is the complete schema with some demo values
What is the best way to find top sold itemName
for each day.
Output would be like date,itemName
.
Best Answer
If you want ties:
If you don't want ties, change
RANK()
toROW_NUMBER()
, just note that it will pick an arbitrary winner unless you add some kind of tie-breaker to theORDER BY
.If you need to fill in gaps in some date range, for example if yesterday had no sales but you still want a row, you can generate a set of dates first, and then use an outer join (this example returns rows from January 1 -> January 15 inclusive):
(Also, do you really think it's productive to make slightly shorter but far more obscure and difficult-to-remember column names like
oDate
anditemQnt
? And why isn't there a unique constraint onorderDetails(orderId, itemId)
? Finally, please stay away from regional, ambiguous formats likemm/dd/yyyy
.)