DECLARE @pilotID INT
SET @pilotID = 1
DECLARE @birthDate DATE
SET @birthDate = (SELECT birthDate FROM Pilot WHERE pilotID = @pilotID)
DECLARE @diffInYears INT
SET @diffInYears = DATEDIFF(yy, @birthDate, GETDATE())
DECLARE @currentBirthDate DATE
SET @currentBirthDate = (DATEADD(yyyy, @diffInYears - 1, @birthDate))
DECLARE @firstSixMonthStart DATE
DECLARE @firstSixMonthEnd DATE
DECLARE @secondSixMonthStart DATE
DECLARE @secondSixMonthEnd DATE
SET @firstSixMonthStart = (DATEADD(dd,-(DAY(DATEADD(m,1,@currentBirthDate))-1),DATEADD(m,1,@currentBirthDate)))
SET @firstSixMonthEnd = (DATEADD(dd, -DAY(DATEADD(m,1,@currentBirthDate)), DATEADD(m,7,@currentBirthDate)))
SET @secondSixMonthStart = (DATEADD(dd,-(DAY(DATEADD(m,1,@currentBirthDate))-1),DATEADD(m,7,@currentBirthDate)))
SET @secondSixMonthEnd = (DATEADD(dd, -DAY(DATEADD(m,1,@currentBirthDate)), DATEADD(m,13,@currentBirthDate)))
DECLARE @semiAnnualStart AS DATE
DECLARE @semiAnnualEnd AS DATE
DECLARE @annualStart AS DATE
DECLARE @annualEnd AS DATE
SET @semiAnnualStart = CASE
WHEN GETDATE() > (DATEADD(dd, -DAY(DATEADD(m,1,@firstSixMonthEnd)), DATEADD(m,7,@firstSixMonthEnd)))
THEN (DATEADD(yyyy, 1, @firstSixMonthStart))
WHEN GETDATE() > @firstSixMonthEnd
THEN @secondSixMonthStart
ELSE @firstSixMonthStart
END
SET @semiAnnualEnd = CASE
WHEN GETDATE() > (DATEADD(dd, -DAY(DATEADD(m,1,@firstSixMonthEnd)), DATEADD(m,7,@firstSixMonthEnd)))
THEN (DATEADD(yyyy, 1, @firstSixMonthEnd))
WHEN GETDATE() > @firstSixMonthEnd
THEN @secondSixMonthEnd
ELSE @firstSixMonthEnd
END
SET @annualStart = CASE
WHEN GETDATE() > @secondSixMonthEnd THEN (DATEADD(yyyy, 1, @firstSixMonthStart))
ELSE @firstSixMonthStart
END
SET @annualEnd = CASE
WHEN GETDATE() > @secondSixMonthEnd THEN (DATEADD(yyyy, 1, @secondSixMonthEnd))
ELSE @secondSixMonthEnd
END
SELECT @semiAnnualStart semiStart, @semiAnnualEnd semiEnd,
@annualStart annualStart, @annualEnd annualEnd,
@firstSixMonthStart firstStart, @firstSixMonthEnd firstEnd,
@secondSixMonthStart secondStart, @secondSixMonthEnd secondEnd,
COUNT(*) semiSorties, ISNULL(SUM(hours), 0) semiSortieHours
FROM PilotLog
WHERE pilotID = @pilotID
AND topLevelPosition = 'AVO'
AND flightDate BETWEEN @semiAnnualStart AND @semiAnnualEnd
结果:
semiStart semiEnd annualStart annualEnd firstStart firstEnd secondStart secondEnd semiSorties semiSortieHours
2012-05-01 2012-10-31 2011-11-01 2012-10-31 2011-11-01 2012-04-30 2012-05-01 2012-10-31 1 1.7
这最终奏效了...问题是,我需要为总体摘要页面上的每个飞行员执行此操作。此外,我将需要为她想要的快照计算这种出击信息。她想回到任何特定月份并查看快照,列出每个航班以及他们完成该航班后的出击统计数据。这个 SQL 应该适用于这些情况,只是我必须在这里和那里稍微改变一下。
(编辑:为什么我的代码不水平滚动..?我不想让它换行。没关系,这只是 Internet Explorer 的样子)