比较SQL中两列或更多列的值

时间:2017-10-25 17:49:21

标签: sql sql-server-2008

我想将列Wk07Filter与相应的列进行比较,直到Wk13 Filter。目标是查找值是否连续绿色超过3次。如果它是绿色超过3次,则意味着它可以使用4周或更长时间。对于例如从Wk10Filter到Wk13Filter的第3行是绿色的,我应该把它写成可用的面板

Wk7Filter Wk8Filter Wk09Filter Wk10Filter Wk11Filter Wk12Filter Wk13Filter
red         red       purpl      black     black      green      green
yello       yello     yello      yello     green      green      green
red         red       red        green     green      green      green
green       green     green      green     green      green      green

enter image description here

1 个答案:

答案 0 :(得分:1)

将所有列连接在一起

WITH cte as (
  SELECT id, ',' + Wk7Filter + 
             ',' + Wk8Filter + 
             ',' + Wk09Filter +
             ',' + Wk10Filter +
             ',' + Wk11Filter +
             ',' + Wk12Filter +
             ',' + Wk13Filter + ',' as filter
 FROM YourTable
)
SELECT id 
FROM cte
WHERE filter like '%,green,green,green,green,%'

超过3个绿色均值为绿色四倍或更多。