2014-05-25 223 views
1

我對病例陳述有點新,但下面是我的查詢。關於where子句的case語句?

Table1 
col1 col2 col3 col4 Month Freeze 
1 13 25 37 1 0 
3 15 27 39 2 1 
4 16 28 40 2 0 
5 17 29 41 3 1 
6 18 30 42 3 0 
7 19 31 43 4 1 
8 20 32 44 4 0 
9 21 33 45 5 1 
10 22 34 46 5 0 
11 23 35 47 6 0 

'結果我要像':

Select all records from Month1 to Month 12 where 'Freeze = 1' , 
if any month between 1 to 12 does not have Freeze = 1 then give me records for Freeze= 0 'just for the months which does not have 'Freeze = 1' 

我最好的非工作的嘗試:

select * from tb1 where Month between 2 and 6 and freeze = 1 or Month in ('1' ,'2') and freeze = 0 
+3

請向我們展示您最好的非工作嘗試。 – dasblinkenlight

+0

@dasblinkenlight:我的查詢是:從TB1 選擇*,其中第2個月和6凍結= 1 或月(「1」,「2」),並凍結= 0 – user3671247

+0

之間我不知道如何實現結果我的情況 – user3671247

回答

0

以下是使用標準SQL的方法:

Select t1.* 
from table1 t1 
where Freeze = 1 and month between 1 and 12 or 
     (not exists (select 1 from table where Freeze = 1 and month between 1 and 12) and 
     month = 0 
    ); 

使用窗口函數,你也可以:

select t1.* 
from (select t1.*, 
      count(case when freeze = 1 and month between 1 and 2) over() as freeze1cnt 
     from table1 t1 
    ) t1 
where month between 1 and 2 and freeze = 1 or 
     month = 0 and freeze1cnt = 0; 
1

下面是將outer join一個選項:

select t1.* 
from Table1 t1 
    left join Table1 t2 on 
    t1.month = t2.month and t2.freeze = 1 
where t1.freeze = 1 
    and t1.month between 1 and 12 
    or t2.month is null 

結果:

COL1 COL2 COL3 COL4 MONTH FREEZE 
1  13  25 37 1  0 
3  15  27 39 2  1 
5  17  29 41 3  1 
7  19  31 43 4  1 
9  21  33 45 5  1 
11 23  35 47 6  0 

注意,根據y的我們的數據,您可能需要使用此方法使用distinct

+1

非常感謝您的時間!所有的答案都是有用的。 – user3671247

+0

@ user3671247 - 不客氣,很高興我們可以提供幫助。 – sgeddes