该解决方案: “缠绕” 了整整一年。 并且还允许“投射多少个月”过滤器。
IF OBJECT_ID('tempdb..#Employee') IS NOT NULL
begin
drop table #Employee
end
CREATE TABLE #Employee
(
SurrogateKeyIDENTITY int not null IDENTITY (1,1) ,
NameOf varchar(12) not null ,
BirthDate datetime not null
)
Insert into #Employee (NameOf, BirthDate)
Select 'A', '01/01/1999'
UNION ALL Select 'B', '01/16/1941'
UNION ALL Select 'C', '01/29/1965'
UNION ALL Select 'D', '02/13/1944'
UNION ALL Select 'P', '02/14/1978'
UNION ALL Select 'Q', '02/15/1984'
UNION ALL Select 'R', '03/13/1948'
UNION ALL Select 'S', '04/16/1983'
UNION ALL Select 'T', '05/17/1953'
UNION ALL Select 'U', '07/19/1959'
UNION ALL Select 'V', '08/16/1959'
UNION ALL Select 'W', '09/1/1959'
UNION ALL Select 'X', '10/30/1959'
UNION ALL Select 'Y', '11/16/1959'
UNION ALL Select 'Z', '12/31/1972'
Declare @MyCURRENT_TIMESTAMP datetime
/* select @MyCURRENT_TIMESTAMP = CURRENT_TIMESTAMP */
select @MyCURRENT_TIMESTAMP = '02/14/2014'
Declare @NumberOfMonthsToGoOut int
select @NumberOfMonthsToGoOut = 12
;WITH myCalculationsCTE (NameOf, BirthDate, [NoYearBirthDate] , [NoYearCurrentDate])
AS
(
SELECT NameOf, BirthDate
, DATEFROMPARTS(1900 , MONTH(BirthDate), DAY (BirthDate)) [NoYearBirthDate]
, DATEFROMPARTS(1900 , MONTH(@MyCURRENT_TIMESTAMP), DAY (@MyCURRENT_TIMESTAMP)) [NoYearCurrentDate]
FROM #Employee
WHERE BirthDate IS NOT NULL
)
,
myCTE (NameOf, BirthDate, [NoYearBirthDate] , [NoYearCurrentDate] , DerivedMonthDiff)
AS
(
SELECT NameOf, BirthDate
, [NoYearBirthDate]
, [NoYearCurrentDate]
, [DerivedMonthDiff] = CASE
WHEN [NoYearBirthDate] >= [NoYearCurrentDate]
then DATEDIFF(m , [NoYearCurrentDate], [NoYearBirthDate])
else
DATEDIFF(m , [NoYearCurrentDate], [NoYearBirthDate]) + 12 end
FROM myCalculationsCTE
)
SELECT NameOf, BirthDate , [NoYearBirthDate] , [NoYearCurrentDate]
, DerivedMonthDiff
, MONTH([NoYearBirthDate]) [Month]
, DAY ([NoYearBirthDate]) [DayOf]
FROM myCTE
where [DerivedMonthDiff] <= @NumberOfMonthsToGoOut
order by DerivedMonthDiff , MONTH([NoYearBirthDate]) , DAY ([NoYearBirthDate])
IF OBJECT_ID('tempdb..#Employee') IS NOT NULL
begin
drop table #Employee
end
请提供样本数据和预期的结果。 –
我编辑了我的问题 – MarceloMadnezz