我需要根据选择的参数拉入某些 dates 。我想不出这是怎么做到的。这个声明有什么我遗漏的东西还是有更好的方法?
Declare @StartDate int = CONVERT(varchar(8), EOMONTH(GETDATE(), -18), 112)
Declare @MonthYear varchar(8) = 2;
select
case when @MonthYear = 2 then
(select DateKey as StartDate
FROM dimDate
where IsLastDayOfYear = 'Y'
and DateKey > 20110101
and DateKey <= CONVERT(varchar(8), EOMONTH(GETDATE(), 0), 112)
Order by DateKey desc
)
when @Monthyear = 1 then
(select DateKey as StartDate
FROM dimDate
where IsLastDayOfMonth = 'Y'
and DateKey > 20110101
and DateKey <= CONVERT(CHAR(8),DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) -0, -1),112)
)
end
这是“看起来”像我想要发生的代码。(我知道它不起作用)我只需要根据参数返回一个或另一个。一个返回每年的最后一天,另一个返回每个月的最后一天
回答1
and DateKey > 20110101 and DateKey <=
case @MonthYear
when 1 then
CONVERT(CHAR(8),DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) -0, -1),112)
when 2 then
CONVERT(varchar(8), EOMONTH(GETDATE(), 0), 112)
end
看起来逻辑的两个“分支”仅在 date 范围的末尾有所不同,这很容易封装在 case
表达式中。我不太确定 -0
以及这些表达式的含义,所以我只是按原样复制了问题。如果您的查询最终变慢,您可能需要设置一个硬上限,以便优化器可以明确限制搜索范围。