我被卡住了!我正在尝试创建一个计数器,当组字段更改时,该计数器再次从1开始:
这就是我想要的:
ProdID Date counter
123 1/1/2016 1
123 1/2/2016 2
123 1/3/2016 3
123 1/4/2016 4
456 1/1/2016 1
456 1/2/2016 2
789 1/1/2016 1
789 1/2/2016 2
789 1/3/2016 3
789 1/4/2016 4
789 1/5/2016 5
当我使用rank()
之后,当prodid发生变化时,是否会重置?
答案 0 :(得分:0)
如果你只是想选择数据,那么这应该会给你这些结果:
SELECT
ProdID,
[Date], -- A poor name for a column, since it's not only a reserved word, but also not at all descriptive
ROW_NUMBER() OVER (PARTITION BY ProdID ORDER BY [Date]) AS counter
FROM
My_Table
PARTITION BY
告诉SQL Server您希望ROW_NUMBER
窗口函数的窗口由ProdID
分区。想象一下,ProdID
将您的数据分成几组。 ORDER BY
告诉它在应用函数之前按Date
对每个窗口中的数据进行排序。
答案 1 :(得分:0)
你试过这个吗?
SELECT ProdId,Date, ROW_NUMBER() OVER
(PARTITION BY ProdID ORDER BY Date DESC)
AS Counter from table
order by Date ASC