我对案例陈述有点新,但下面是我的查询。
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
答案 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
注意,根据您的数据,您可能需要使用此方法distinct
。
答案 1 :(得分: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;