在大小写表达式中调用别名



我有这个代码,每个月检查这个人是否在该月注册,最后应该告诉你这个人是否注册了一整年。Annual是每个月检查他们是否有来自 case 表达式1。问题是我无法让 SQL 识别别名,例如JanFeb

Select SSN, FirstName, LastName,
Case (DateEnrolled > '1-1-2019' and DateEnrolled < '1-31-2019' ) then 1 else 0 as [Jan],
Case (DateEnrolled > '2-1-2019' and DateEnrolled < '2-28-2019') then 1 else 0 as [Feb],
...
Case (Jan = 1 AND Feb = 1 AND...) then 1 else 0 as [Annual]
from EmployeePerson

试试这个:

with cte as
(
Select SSN, FirstName, LastName,
Case (DateEnrolled > '1-1-2019' and DateEnrolled < '1-31-2019' ) then 1 else 0 end as [Jan],
Case (DateEnrolled > '2-1-2019' and DateEnrolled < '2-28-2019') then 1 else 0 end as [Feb],
...
from EmployeePerson
)
select SSN, FirstName, LastName, [Jan], [Feb]...,[Dec],
Case (Jan = 1 AND Feb = 1 AND...AND [Dec] = 1) then 1 else 0 end as [Annual]
from cte 

试试这个! 选择 SSN, 名字, 姓氏, 当(注册日期> '01-01-2019' 和注册日期<'01-31-2019'(然后是"1 月", 案例当(注册日期>'02-01-2019'和注册日期<'02-28-2019'(然后"二月" 结尾为"年度" 来自员工;

我认为这会有所帮助。

试试

select SSN, FirstName,
Case when Jan is null then 0 else 1 end as Jan,
Case when Feb is null then 0 else 1 end as Feb,
Case when Mar is null then 0 else 1 end as Mar,
Case when Apr is null then 0 else 1 end as Apr,
Case when May is null then 0 else 1 end as May,
Case when Jun is null then 0 else 1 end as Jun,
Case when Jul is null then 0 else 1 end as Jul,
Case when Aug is null then 0 else 1 end as Aug,
Case when Sep is null then 0 else 1 end as Sep,
Case when Oct is null then 0 else 1 end as Oct,
Case when Nov is null then 0 else 1 end as Nov,
Case when [Dec] is null then 0 else 1 end as [Dec],
Case when ([Jan] is not null AND [Feb] is not null AND [Mar] is not null AND 
[Apr] is not null AND [May] is not null AND [Jun] is not null AND 
[Jul] is not null AND [Aug] is not null AND [Sep] is not null AND 
[Oct] is not null AND [Nov] is not null AND [Dec] is not null) then 1 else 0 end as Annual
from(
Select SSN, FirstName, format(DateEnrolled, 'MMM') Enrolled
from EmployeePerson)aa 
pivot (max(Enrolled) for Enrolled in([Jan], [Feb], [Mar], [Apr], [May], [Jun], [Jul], [Aug], [Sep], [Oct], [Nov], [Dec])) as dtl

最新更新