开发者

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

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   &nbs开发者_运维技巧p;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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜