簡體   English   中英

在 case 表達式中調用別名

[英]Call an alias in a case expression

我有這個代碼是每個月檢查這個人是否在那個月注冊,最后它會告訴你這個人是否全年都注冊了。 Annual將檢查每個月是否有案例表達式中的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, FirstName, LastName, CASE WHEN (DateEnrolled > '01-01-2019' AND DateEnrolled < '01-31-2019') THEN 'Jan', CASE WHEN (DateEnrolled > '02-01-2019' AND DateEnrolled < '02-28-2019') THEN 'Feb' 以 'Annual' 從 EmployeePerson 結束;

我認為這會有所幫助。

嘗試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM