SQL视图用case创建动态列

时间:2017-06-26 19:08:58

标签: sql

我有以下SQL查询,我试图查询相同的表但具有不同的条件。我正在尝试加快输出以过滤输出。

select column1, column2 
from table 
where column2 like abc 
  and column3 = '1' 

select column1, column2 
from table 
where column2 like abc 
  and column4 = '1' 
  and column5 = 'car' 

select column1, column2 
from table
where column2 like abc 
  and column6 = 'country' 
  and column7 = 'food'

我正在寻找一个切换案例来创建一个带有附加列10的视图,并为第一个查询的输出放置一个条目,并为后续查询执行相同操作。

最终视图应该是这样的,

column1 column2 column3 
Red     Mar     Rule1 
Blue    Earth   Rule2
Green   Venus   Rule2 
White   Pluto   Rule1 
Pink    Jupitor Rule2

示例示例:

SELECT column1, column2, CASE WHEN column2 like '%abc%' and column3 = '1' 
THEN 'Rule1' WHEN column2 like '%abc%' and column4 = '1' and column5 = 'car' 
THEN 'Rule2' WHEN column2 like '%abc%' and column6 = 'country' amd column7 = 'food' 
THEN 'Rule3' END AS RuleName FROM table

0 个答案:

没有答案