如何解决如何在 where 子句中使用 case 语句别名
我试图在别名中使用 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 子句中使用别名。我在搜索中看不到如何做到这一点。我需要返回非主要的空“类型”。有多种情况,而不仅仅是服务表中的一种。
解决方法
您可以将初始查询作为 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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。