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

浪尽此生 提交于 2019-12-01 09:48:48

问题


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 the table below, the "Order" field would restart at "1" every time there was a change in the "Meal" field. Thanks.

Meal      Time    Order
Lunch    10:30     1
Lunch    11:00     2
Lunch    11:15     3
Dinner    4:30      1
Dinner    4:45      2
Dinner    5:00      3
Dinner    5:30      4


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/7407615/auto-increment-field-that-resets-after-a-change-in-another-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!