如何在 where 子句中使用 case 语句别名
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 子句中使用别名。我在搜索中看不到如何做到这一点。我需要 return 不是主要的空“类型”。有多种情况,不仅仅是服务中的一种情况 table。
您可以将初始查询作为 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)
我试图在别名中使用 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 子句中使用别名。我在搜索中看不到如何做到这一点。我需要 return 不是主要的空“类型”。有多种情况,不仅仅是服务中的一种情况 table。
您可以将初始查询作为 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)