I have a order table that stores order meta include their date, sample data like the following
date |order-id
2010-12-16|106
2010-12-18|112
2009-03-05|115
2009-03-05|122
now I need to create folder that groups all the orders from the same month and pick the first order in the month as showcase, but it appears group by always pick the last row in my query below
SELECT orders.id, order.date from orders
GROUP BY strftime('%Y-%m', orders.date)
it returns the last row of each month
2010-12-18|112
2009-03-05|122
so I’d like it to return
2010-12-16|106
2009-03-05|115
(106: earlier in the month)
(115: same date as the other one, but this will match the 1st one if I do a sorted order query for the month)
I tried the JOIN query, it works if I don’t have multiple orders on the same day, but in the case of 2009-03, it still returns the last row, instead of the first row…
SELECT o.id, o.date
FROM orders o
JOIN
(SELECT MIN(date) as first_date FROM orders
GROUP BY strftime('%Y-%m', orders.date)
) as sorted_orders
ON o.creation_date=sorted_order.first_date
GROUP BY strftime('%Y-%m', orders.date)
Anything else I can try?
Your second query does not work because you are not actually selecting any column from the
sorted_orderssubquery.Anyway, if you have SQLite 3.7.11 or later, records in a
GROUP BYquery are guaranteed to come from the record in a group that matches aMINorMAXfor that group: