增加一年的账单,并在新的一年再次将其重置为1

时间:2017-09-17 05:06:28

标签: sql

我试过这个 -

SELECT top(1)billreference
FROM BIll
WHERE datepart(yy,date)=datepart(yy,getdate())
ORDER BY billreference DESC

当我增加9

时,它总是返回1

我想将billrefernece number增加1,因为它不是identity列 我正在做这个因为我需要在1更改后将其重置为year并在整年内增加.. 任何帮助将不胜感激..

1 个答案:

答案 0 :(得分:0)

假设您的表格中的数据位于date列,如下所示。

      date1
-------------------
01.01.2016 00:00:00
01.01.2016 00:00:00
01.01.2016 00:00:00
01.01.2016 00:00:00
01.01.2017 00:00:00
01.01.2017 00:00:00
01.01.2017 00:00:00
01.01.2017 00:00:00

并且您希望在同一年将billreference递增1,并在year更改时重置,在查询下方可以是sql-server中的选项。

SELECT row_number() over(partition BY datepart(yy,date1)
                         ORDER BY date1) AS billreference,
       date1
FROM t1;

对于其他dbms,可以使用ANSI标准extract(year from datecolumn)代替datepart

<强>结果:

billreference        date1
-----------------------------------
1              01.01.2016 00:00:00
2              01.01.2016 00:00:00
3              01.01.2016 00:00:00
4              01.01.2016 00:00:00
1              01.01.2017 00:00:00
2              01.01.2017 00:00:00
3              01.01.2017 00:00:00
4              01.01.2017 00:00:00

您可以查看演示 here