我正在尝试为来自DTBL_SCHOOL_DATES表的特定日期设置季节范围。下面是我的逻辑,它基于年份及其地区来设置每个给定范围的季节。
CASE
WHEN RTRIM(dtbl_school_dates.local_school_year) = '2021-2022' THEN
CASE
WHEN RTRIM(dtbl_schools_ext.region) = 'Bay Area' AND
CAST(dtbl_school_dates.date_value AS DATE) BETWEEN '08/07/2021' and '09/08/2021' THEN 'FALL'
WHEN RTRIM(dtbl_schools_ext.region) = 'Bay Area' AND
CAST(dtbl_school_dates.date_value AS DATE) BETWEEN '11/27/2021' and '12/15/2021' THEN 'WINTER'
WHEN RTRIM(dtbl_schools_ext.region) = 'Bay Area' AND
CAST(dtbl_school_dates.date_value AS DATE) BETWEEN '03/04/2022' and '03/22/2022' THEN 'SPRING'
WHEN RTRIM(dtbl_schools_ext.region) = 'Central Valley' AND
CAST(dtbl_school_dates.date_value AS DATE) BETWEEN '07/31/2021' and '09/01/2021' THEN 'FALL'
WHEN RTRIM(dtbl_schools_ext.region) = 'Central Valley' AND
CAST(dtbl_school_dates.date_value AS DATE) BETWEEN '11/27/2021' and '12/15/2021' THEN 'WINTER'
WHEN RTRIM(dtbl_schools_ext.region) = 'Central Valley' AND
CAST(dtbl_school_dates.date_value AS DATE) BETWEEN '02/19/2022' and '03/08/2022' THEN 'SPRING'
WHEN RTRIM(dtbl_schools_ext.region) = 'Los Angeles' AND
CAST(dtbl_school_dates.date_value AS DATE) BETWEEN '08/14/2021' and '09/15/2021' THEN 'FALL'
WHEN RTRIM(dtbl_schools_ext.region) = 'Los Angeles' AND
CAST(dtbl_school_dates.date_value AS DATE) BETWEEN '11/27/2021' and '12/15/2021' THEN 'WINTER'
WHEN RTRIM(dtbl_schools_ext.region) = 'Los Angeles' AND
CAST(dtbl_school_dates.date_value AS DATE) BETWEEN '03/04/2022' and '03/22/2022' THEN 'SPRING'
ELSE 'NOT IN RANGE'
END
ELSE FTBL_TEST_SCORES.test_admin_period
END AS "C4630"
但只要日期不在逻辑指定的范围内,我希望它们被忽略。AKA,值NOT IN RANGE应该被排除。我尝试使用FTBL_TEST_SCORES。test_admin_period不为空,它们不会工作,因为没有来自数据库的值为空。
NOT IN RANGE VALUE SHOULD BE excluded in results, how do I achieve that in where clause
我尝试使用Alias进行限制,但不起作用。我不确定是否可以在case语句(如Case when 'a' then field ='B' end)中为特定字段赋值
不在范围内的值应排除在结果之外,如何在where子句中实现这一点
2条答案
按热度按时间nhhxz33t1#
您可以在WHERE子句中重复整个CASE语句,如下所示:
也可以使用如下子查询(或CTE):
3zwtqj6y2#
如果不能看到完整的查询,就不可能给出“最优”的解决方案,最简单的解决方案是将条件添加为
HAVING
子句:我对你的日期格式感到困惑。如果这应该是一个MySQL查询,它们应该是
yyyy-mm-dd
。可以说,即使在SQL Server上,它们也应该是这种格式,因为SQL Server支持不明确的本地日期格式。为什么要使用
RTRIM
和CAST
?数据应该以正确的格式存储,并在输入时进行清理,如果无法做到这一点,请定期清理数据,而不是对每个查询都进行清理。明智的做法是将
seasons
移到它们自己的表中,而不是在查询时定义它们,这样就可以简单地连接到seasons
,我在这里使用了一个子查询,但希望您能理解: