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

前端 未结 2 1886
太阳男子
太阳男子 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:14

    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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题