[英]How use case statement alias in where clause
我正在嘗試在別名中使用 case 語句和結果,但我需要在 where 子句中使用別名,這似乎不起作用。 如何在 where 子句中使用別名(下面的 isPrimary)。 請參閱我在 where 子句中嘗試使用 isPrimary 的評論,這不起作用。 如何在 where 子句中使用別名?
CREATE TABLE #cases
(
id varchar(25),
CASEID VARCHAR(12)
)
#cases:
id caseid
15 12345
15 23456
CREATE TABLE #services
(
id varchar(25),
CASEID VARCHAR(12),
createdate VARCHAR(30),
types int
)
#services:
id caseid createdate types
15 12345 2021-04-27 11:59:01.333 null --this is the primary one
16 12345 2021-04-28 07:37:20.163 null
17 12345 2021-04-28 07:55:08.750 10
select c.caseid,
CASE WHEN sv.id = (SELECT Top 1 ID FROM #services WHERE caseid = c.caseid ORDER BY createdate ASC) THEN 1 ELSE 0 END AS isPrimary --if lowest date for sv.caseid then label "1", otherwise "0"
from
#cases c
left join #services sv on sv.caseid=c.caseid
where
(isPrimary=0 and types is null) --it doesn't want me to use the alias here
我正在查看[case alias where][1]
但它沒有嘗試在 where 子句中使用別名。 我在搜索中看不到如何做到這一點。 我需要返回不是主要的 null “類型”。 有多種情況,而不僅僅是服務表中的一種。
您可以將初始查詢作為CTE來獲取別名,然后在結果數據集上使用您的WHERE
條件。
;with cte
as (
select c.caseid, types,
CASE WHEN sv.id = (SELECT Top 1 ID FROM #services WHERE caseid = c.caseid ORDER BY createdate ASC) THEN 1 ELSE 0 END AS isPrimary
from
#cases c
left join #services sv on sv.caseid=c.caseid)
select *
from cte
where
(isPrimary=0 and types is null)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.