SQL - 计算两个日期之间的频率(每月,每季度和每年)

时间:2017-08-16 11:53:01

标签: sql sql-server sql-server-2008

在SQL Server中,我有两个日期列x和y列,我想计算这两个日期之间的频率,如果是每月,每季度或每年。

我试过自己,但似乎不正确

代码:

CASE WHEN ROUND(DATEDIFF(d, ISNULL(RV.[x], ''), ISNULL(RV.[y], ''))/30.0, 1) <= 1 THEN 'MONTHLY'    
     WHEN ROUND(DATEDIFF(d, ISNULL(RV.[x], ''), ISNULL(RV.[y], ''))/30.0, 1) BETWEEN 1 AND 3 THEN 'QUARTERLY'   
     ELSE 'ANNUALLY'  
END  FREQUENCY

如果有人能帮我正确编码,我将不胜感激。

谢谢,非常感谢

1 个答案:

答案 0 :(得分:0)

如果你在日期的某些NULL值的模拟数据上运行它,你会注意到DATEDIFF有时会返回负值。
这将使CASE返回&#34;每月&#34;出于错误的原因。

不要做ISNULL。这样,DATEDIFF将为那些返回NULL并被评估为&#34;年度&#34;。

此外,您还可以在f.e.中获取DATEDIFF。几个月,这可以简化您的查询。

declare @TestTable table (x date, y date);

declare @y date = '2017-08-15'; 

insert into @TestTable (x,y) values
(dateadd(day,-10,@y),@y),
(dateadd(day,-30,@y),@y),
(dateadd(day,-60,@y),@y),
(dateadd(day,-240,@y),@y),
(null,@y),
(dateadd(month,-2,@y),null);

select RV.*,
/* 
DATEDIFF(day, RV.[x], RV.[y]) as monthdiff,
DATEDIFF(month, RV.[x], RV.[y]) as monthdiff,
DATEDIFF(quarter, RV.[x], RV.[y]) as quarterdiff,
DATEDIFF(year, RV.[x], RV.[y]) as yeardiff,
*/
CASE 
 WHEN DATEDIFF(month, RV.[x], RV.[y]) = 0 THEN 'MONTHLY'  
 WHEN DATEDIFF(quarter, RV.[x], RV.[y]) = 0 THEN 'QUARTERLY'
 WHEN DATEDIFF(year, RV.[x], RV.[y]) = 0 THEN 'ANNUALLY'
 ELSE 'ANNUALLY?'
END FREQUENCY
from @TestTable RV;

返回:

x           y           FREQUENCY
----------  ----------  ----------
2017-08-05  2017-08-15  MONTHLY
2017-07-16  2017-08-15  QUARTERLY
2017-06-16  2017-08-15  ANNUALLY
2016-12-18  2017-08-15  ANNUALLY?
NULL        2017-08-15  ANNUALLY?
2017-06-15  NULL        ANNUALLY?

还检查此测试SQL的结果:

select RV.*, 
DATEDIFF(day, x, y) as daydiff,
DATEDIFF(month, x, y) as monthdiff,
DATEDIFF(quarter, x, y) as quarterdiff,
case when DATEDIFF(quarter, RV.[x], RV.[y]) = 0 then 'yes' else 'no' end as same_quarter
from (values 
('2017-01-15','2017-03-31'),
('2017-01-15','2017-04-01')
) as RV(x,y);