Can you provide a very simple SQL example of how to create a \"count\" or \"order\" field that would auto-increment, but restart after every change in a different field? In
Instead of storing Order
in the table, consider adding it to a view. You can select from the view instead of the table when you need it.
The view could use row_number()
to calculate the order, like:
select row_number() over (partition by Meal order by Time)
, *
from YourTable
Example at SE Data.
That's not something that you should be storing in the database. You're basically storing the same information twice (in this case it's derived, but effectively the same) which will likely result in problems down the road. You're going to end up with a new Lunch row before the last one and the order numbers will be screwed up, etc. Instead, just calculate the number when you need it.
You don't mention which RDBMS you're using (always a good idea to include that information when asking a question), but something like the following will work with SQL Server and other RDBMSs that support partition functions:
SELECT
meal,
[time], -- I'd pick a better column name myself. Reserved words = evil
ROW_NUMBER() OVER(PARTITION BY meal ORDER BY time) AS [order] -- Another reserved word! Eeek!
FROM
My_Table