Auto-increment field that resets after a change in another field

前端 未结 2 1907
太阳男子
太阳男子 2021-01-16 07:31

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

2条回答
  •  甜味超标
    2021-01-16 08:24

    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
    

提交回复
热议问题