Sql 行号()基于日期
我有以下数据:Sql 行号()基于日期,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有以下数据: test_date 2018-07-01 2018-07-02 ... 2019-06-30 2019-07-01 2019-07-02 ... 2020-06-30 2020-07-01 我想在每次right(test\u date,5)=“07-01”时增加一个row\u number值,这样我的最终结果如下所示: test_date row_num 2018-07-01 1 2018-07-02 1 ...
test_date
2018-07-01
2018-07-02
...
2019-06-30
2019-07-01
2019-07-02
...
2020-06-30
2020-07-01
我想在每次right(test\u date,5)=“07-01”
时增加一个row\u number
值,这样我的最终结果如下所示:
test_date row_num
2018-07-01 1
2018-07-02 1
... 1
2019-06-30 1
2019-07-01 2
2019-07-02 2
... 2
2020-06-30 2
2020-07-01 3
, ROW_NUMBER() OVER (
PARTITION BY CASE WHEN RIGHT(a.[test_date],5) = '07-01' THEN 1 ELSE 0 END
ORDER BY a.[test_date]
) AS [test2]
我试过这样做:
test_date row_num
2018-07-01 1
2018-07-02 1
... 1
2019-06-30 1
2019-07-01 2
2019-07-02 2
... 2
2020-06-30 2
2020-07-01 3
, ROW_NUMBER() OVER (
PARTITION BY CASE WHEN RIGHT(a.[test_date],5) = '07-01' THEN 1 ELSE 0 END
ORDER BY a.[test_date]
) AS [test2]
但这对我来说不起作用
有什么建议吗?用于确定正确的日期,然后在每次更改时向总和中添加1(假设每个日期的行数永远不会超过1行)
注意:如果像我上面所做的那样,将示例数据添加为DDL+DML,人们可以更容易地进行测试。用于标识正确的日期,然后在每次更改时向总和添加1(假设每个日期的行数永远不会超过1行)
注意:如果像我上面所做的那样,将样本数据添加为DDL+DML,人们可以更容易地进行测试。如果从日期中减去6个月,您可以使用
densite_RANK()
窗口函数进行测试:
SELECT test_date,
DENSE_RANK() OVER (ORDER BY YEAR(DATEADD(month, -6, test_date))) row_num
FROM tablename
请参阅。结果:
如果从日期中减去6个月,则可以使用
densite\u RANK()
窗口函数执行此操作:
SELECT test_date,
DENSE_RANK() OVER (ORDER BY YEAR(DATEADD(month, -6, test_date))) row_num
FROM tablename
请参阅。结果:
根据月=7天=2建立一个运行总数
declare @Test table (mykey int,test_date date);
insert into @Test (mykey,test_date)
values
(1,'2018-07-01'),
(2,'2018-07-02'),
(3,'2019-06-30'),
(4,'2019-07-01'),
(5,'2019-07-02'),
(6,'2020-06-30'),
(7,'2020-07-01');
select mykey,test_date,
sum(case when DatePart(Month,test_date)=7 and DatePart(Day,test_date)=2 then 1 else 0 end) over (order by mykey) RunningTotal from @Test
order by mykey
根据月=7天=2建立一个运行总数
declare @Test table (mykey int,test_date date);
insert into @Test (mykey,test_date)
values
(1,'2018-07-01'),
(2,'2018-07-02'),
(3,'2019-06-30'),
(4,'2019-07-01'),
(5,'2019-07-02'),
(6,'2020-06-30'),
(7,'2020-07-01');
select mykey,test_date,
sum(case when DatePart(Month,test_date)=7 and DatePart(Day,test_date)=2 then 1 else 0 end) over (order by mykey) RunningTotal from @Test
order by mykey