0

我有一个带有 Union 语句的查询,只是为了检查大小写,但我想在 Where 中实现 CASE,但我是 SQL 的初学者,不知道我该怎么做。

我的查询就像

SELECT TOP 1 EndDate
           FROM   (
                      SELECT 1 AS seq,

                             EndDate,

                      FROM   pipeline_rest_envr_info e
                      WHERE  e.tckt_id = imt.tckt_id
                             AND stat = 'INPR'
                      UNION
                      SELECT TOP 1 2 AS seq,

                             EndDate,

                      FROM   pipeline_rest_envr_info e
                      WHERE  e.tckt_id = imt.tckt_id
                             AND stat = 'CMPL'
                      ORDER BY
                             enddate DESC
                      UNION
                      SELECT TOP 1 3 AS seq,

                             EndDate,

                      FROM   pipeline_rest_envr_info e
                      WHERE  e.tckt_id = imt.tckt_id
                             AND stat = 'PLND'
                      ORDER BY
                             strt_dt
                      UNION 
                      SELECT 4 AS seq,

                             NULL,

                      FROM   pipeline_rest_envr_info e
                      WHERE  e.tckt_id = imt.tckt_id
                  ) aa
           ORDER BY
                  aa.seq
4

3 回答 3

2

SELECT TOP 1 EndDate
FROM(
选择(当 stat = 'INPR' 然后 1
当 stat = 'CMPL' 然后 2
当 stat = 'PLND' 然后 3
else 4 end
)作为 seq,EndDate
from pipeline_rest_envr_info e
left external join table2name imt on e.tckt_id = imt.tckt_id
) aa
ORDER BY
aa.seq

于 2012-07-20T12:31:59.247 回答
0

SELECT TOP 1 aa.*
FROM (
select (case when condition1 then result1
when condition2 then result2
...
else
default_result
end ) as result,... from tablename
) aa
ORDER BY
aa.seq

于 2012-07-20T12:24:48.557 回答
0

避免在 WHERE 中执行 CASE。而是在 SELECT 中应用它。此外,您还没有提到代表别名 IMT 的表

SELECT TOP 1 EndDate
FROM (
select
(
case when stat = 'INPR' then 1
when stat = 'CMPL' then 2
when stat = 'PLND' then 3
else 4 end
) as seq, EndDate
from pipeline_rest_envr_info e
内连接 不管表名是什么.tckt_id = imt.tckt_id
) aa
ORDER BY aa.seq

于 2012-07-20T12:40:36.503 回答