簡體   English   中英

SQL:大於或等於基於案例條件的where子句?

[英]SQL: Greater than or equal to in where clause based on case condition?

我想選擇這樣,如果@reporteetype'immediate'那么我想選擇level 等於 1的行,否則level 大於 2。

select a, b, c, level
from table1
where col1 ='x' and                              
      CASE @reporteetype WHEN 'immediate' THEN level = '2'   
                         WHEN 'other' THEN level > 2
                         else 1 = 1
      END 

這是我的方案的簡化版本。 我不想使用動態查詢。 我想知道這是否可以用案例來完成?

您可以使用ANDOR條件的組合來執行此操作:

SELECT
    a, b, c, level
FROM table1
WHERE
    col1 = 'x'
    AND (
        (@reporteetype = 'immediate' AND level = 2)
        OR (@reporteetype = 'other' AND level > 2)
    )

補充閱讀:

Gail Shaw抓住了所有的查詢

@Felix建議的答案Pamittan更有效,但是如果你想使用CASE Expression,那么它會有所幫助:

SELECT  a
      , b
      , c
      , level
FROM    table1
WHERE   col1 = 'x'
        AND ( ( CASE WHEN @reporteetype = 'immediate' THEN '2'
                END ) = level
              OR ( CASE WHEN @reporteetype = 'other' THEN '2'
                   END ) > level
            )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM