根据另一个WHERE(条件)选择使用哪个WHERE(条件)

时间:2018-04-13 02:42:35

标签: sql sql-server

我目前正在研究现有的PIVOT表。我想根据(选择哪个)列值进行选择。要选择哪一列,它基于另一个条件。我举个例子:

@InputCharacter;

Select * from Table_A 

IF @InputCharacter  = 'a'
WHERE column_1 = 1 --Use this condition if @InputCharacter equal to a

ELSE IF @InputCharacter  = 'b'
WHERE column_2 = 1 --Use this condition if @InputCharacter equal to b

ELSE
WHERE column_3 = 1 --Use this condition if @InputCharacter equal to other value

我尝试在网络和Stackoverflow上搜索,但也许我不知道用于搜索的完美关键字,所以我来问这个问题。

1 个答案:

答案 0 :(得分:1)

我认为您可以使用ORCASE

-- 1
SELECT *
FROM Table_A
WHERE (@InputCharacter = 'a' AND column_1 = 1)
   OR (@InputCharacter = 'b' AND column_2 = 1)
   OR (ISNULL(@InputCharacter,'') NOT IN ('a','b') AND column_3 = 1)

-- 2
SELECT *
FROM Table_A
WHERE
    CASE
      WHEN @InputCharacter = 'a' THEN IIF(column_1 = 1,1,0)
      WHEN @InputCharacter = 'b' THEN IIF(column_2 = 1,1,0)
      WHEN column_3 = 1 THEN 1
      ELSE 0
    END = 1

-- 3
SELECT *
FROM Table_A
WHERE
    CASE @InputCharacter
      WHEN 'a' THEN IIF(column_1 = 1,1,0)
      WHEN 'b' THEN IIF(column_2 = 1,1,0)
      ELSE IIF(column_3 = 1,1,0)
    END = 1