Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Auto assign a number to duplicating values that resets after a change in the values WITHOUT using ROW_NUMBER or Partition BY?

I would like 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 RowNumb
Lunch 10:30 1
Lunch 11:00 2
Lunch 11:30 3
Dinner 4:30 1
Dinner 5:00 2
Dinner 5:30 3
Dinner 6:00 4

I tried this:

SELECT
    t1.meal,
    COUNT(t2.meal) + 1 AS RowNumb
FROM CTE t1
JOIN CTE t2 ON t2.time < t1.time OR (t2.time = t1.time AND t2.meal <> t1.meal)
GROUP BY
    t1.time,
    t1.meal
ORDER BY
    t1.time;

But I am getting this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Meal Time RowNumb
Lunch 10:30 1
Lunch 11:00 2
Lunch 11:30 3
Dinner 4:30 4
Dinner 5:00 5
Dinner 5:30 6
Dinner 6:00 7

>Solution :

Use a subquery to count the rows for the same meal and a time till then:

SELECT
  t.meal,
  t.time,
  (
    SELECT COUNT(*)
    FROM mytable t2
    WHERE t2.meal = t.meal
    AND t2.time <= t.time
  ) AS rownumb
FROM mytable t
ORDER BY t.meal, t.time;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading