在 case 表达式中调用别名

Call an alias in a case expression

我有这个代码,每个月都会检查这个人是否在那个月注册,最后它应该告诉你这个人是否全年都在注册。 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 

试试这个! SELECT SSN、名字、姓氏、 CASE WHEN (DateEnrolled > '01-01-2019' AND DateEnrolled < '01-31-2019') 然后 'Jan', CASE WHEN (DateEnrolled > '02-01-2019' AND DateEnrolled < '02-28-2019') 然后 'Feb' 结束为 'Annual' 来自员工;

我认为这会有所帮助。

尝试

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