如何在SQL中使用CASE优化查询

时间:2012-07-20 11:28:22

标签: sql-server

我有一个关于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

3 个答案:

答案 0 :(得分:2)

SELECT TOP 1 EndDate
           FROM(
           选择(当stat ='INPR'然后1为时的情况                        当stat ='CMPL'然后2
                       当stat ='PLND'然后3
                       否则4结束
                     )作为seq,EndDate
            来自pipeline_rest_envr_info e
           在e.tckt_id = imt.tckt_id上留下外连接table2name imt                   )aa
           订购单                   aa.seq

答案 1 :(得分:0)

SELECT TOP 1 aa。*
           FROM(
           select(条件1的情况,然后是result1
                        当condition2然后result2
                        ......                         否则
                        default_result
                        结果,...来自tablename
                  )aa
           订购单                   aa.seq

答案 2 :(得分:0)

避免在WHERE中实现CASE。而是将其应用于SELECT。此外,您还没有提到表示别名IMT的表格

SELECT TOP 1 EndDate
FROM(
选择

stat =' INPR'然后1
     当stat =' CMPL'然后2
     当stat =' PLND'然后3
     否则4结束
)作为seq,EndDate
来自pipeline_rest_envr_info e
内部联接whateverthetablenameis imt on e.tckt_id = imt.tckt_id
)aa
订购aa.seq