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

huangapple go评论60阅读模式
英文:

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

问题

我想创建一个“计数”或“顺序”字段,它会自动递增,但在不同字段发生变化时重新开始。在下表中,“Order”字段将在“Meal”字段发生变化时重新从“1”开始。谢谢。

我尝试了以下代码:

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;

但我得到了以下结果:

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
英文:

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 &lt; t1.time OR (t2.time = t1.time AND t2.meal &lt;&gt; t1.meal)
GROUP BY
    t1.time,
    t1.meal
ORDER BY
    t1.time;

But I am getting this:

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

答案1

得分: 2

使用子查询来计算相同餐点和截止时间之前的行数:

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;
英文:

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 &lt;= t.time
  ) AS rownumb
FROM mytable t
ORDER BY t.meal, t.time;

huangapple
  • 本文由 发表于 2023年5月25日 19:14:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76331678.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定