Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何在where子句中使用case语句别名_Sql_Case_Where Clause_Alias - Fatal编程技术网

Sql 如何在where子句中使用case语句别名

Sql 如何在where子句中使用case语句别名,sql,case,where-clause,alias,Sql,Case,Where Clause,Alias,我试图在别名中使用case语句和结果,但我需要在where子句中使用别名,这似乎不起作用。我如何在where子句中使用别名(如下所示)。请参阅我试图在where子句中使用isPrimary的注释,它不起作用。如何在where子句中使用别名 CREATE TABLE #cases ( id varchar(25), CASEID VARCHAR(12) ) #cases: id caseid 15 12345 15 23456 CREATE TABLE #service

我试图在别名中使用case语句和结果,但我需要在where子句中使用别名,这似乎不起作用。我如何在where子句中使用别名(如下所示)。请参阅我试图在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子句中使用别名。我不知道如何在我的搜索中做到这一点。我需要返回非主要的空“类型”。有多种情况,而不仅仅是服务表中的情况。

您可以将初始查询作为获取别名的条件,然后对生成的数据集使用
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)

SQL中没有所谓的
CASE
语句。你的意思似乎是一个
大小写
表达式。@stickybit:不要在Reddit上提到这个。我曾经看到有人因为那句话被否决了(“谁知道那个”,“我为什么会在乎”)谢谢你们!我从来不知道我能做到。好主意。:)很高兴它对你有用。