I在1975年至2020年的D_Term维度中,每个学期(春季,夏季,秋季)都有学期开始和结束日期。例如:
2017-01-16 to 2017-05-18 (Spring)
2017-06-05 to 2017-08-04 (Summer)
2017-08-24 to 2017-12-20 (Fall)
我目前的问题是我需要创建一个化妆表,其中起始和结束期限为:01/01至05/31(春季),夏季期间为06/01至08/31,秋季期限为这是需要反映学年是什么。这个想法是消除两个连续学期之间的学期结束日期(春季)和学期开学日期(夏季)之间的差距。
我不知道如何去做。欢迎任何想法!
谢谢
首先是一点测试数据:
CREATE TABLE #dates (TermStart DATE, TermEnd DATE, Term VARCHAR(20))
INSERT INTO #dates (TermStart, TermEnd, Term)
VALUES ('2017-01-16','2017-05-18','spring'),
('2017-06-05','2017-08-04','summer'),
('2017-08-24','2017-12-20','fall')
然后是解决方案:
SELECT
Term
, TermStart
, TermEnd
, NewStart = CASE WHEN LAG(DATEPART(MONTH,DATEADD(DAY,DATEPART(DAY,TermEnd)*-1,DATEADD(MONTH,1,TermEnd)))) OVER (ORDER BY TermStart ASC) = DATEPART(MONTH,TermStart)
THEN DATEADD(MONTH,1,DATEADD(DAY,1,DATEADD(dd,DATEPART(DAY,TermStart)*-1,TermStart)) )
ELSE DATEADD(DAY,1,DATEADD(dd,DATEPART(DAY,TermStart)*-1,TermStart))
END
, NewEnd = DATEADD(DAY,DATEPART(DAY,TermEnd)*-1,DATEADD(MONTH,1,TermEnd))
FROM #dates
结果:
Term TermStart TermEnd NewStart NewEnd
------------------------------------------------------
spring 2017-01-16 2017-05-18 2017-01-01 2017-05-31
summer 2017-06-05 2017-08-04 2017-06-01 2017-08-31
fall 2017-08-24 2017-12-20 2017-09-01 2017-12-31
我试过这个,它有效:)
with cte as
(
SELECT
New_Academic_Term_Start_DTTM = CASE WHEN Academic_Term_Code like 'SPRING'
then
concat(year(Academic_Term_Start_DTTM),'-','01','-','01')
WHEN Academic_Term_Code like 'SUMMER'
then
concat(year(Academic_Term_Start_DTTM),'-','06','-','01')
WHEN Academic_Term_Code like 'FALL'
then
concat(year(Academic_Term_Start_DTTM),'-','08','-','21')
end
from D_Term
)
select
convert(datetime2(7),New_Academic_Term_End_DTTM,120) as
New_Academic_Term_End_DTTM
from cte