Sql 基于列值有条件地选择行
从该表中,对于每个范围_ID,我需要使用以下条件选择行: 如果存在除ID字段外具有相同列的行,则仅选择具有FLAG_LINE=1的行;如果存在相同的行,但其中没有一行包含FLAG_LINE=1列,则选择所有行,基于此,查询应返回以下结果:Sql 基于列值有条件地选择行,sql,oracle,plsql,oracle10g,Sql,Oracle,Plsql,Oracle10g,从该表中,对于每个范围_ID,我需要使用以下条件选择行: 如果存在除ID字段外具有相同列的行,则仅选择具有FLAG_LINE=1的行;如果存在相同的行,但其中没有一行包含FLAG_LINE=1列,则选择所有行,基于此,查询应返回以下结果: ID RANGE_ID START_DATE END_DATE BAND_TYPE FLAG_LINE 3 1 01/03/2013 31/03/2013
ID RANGE_ID START_DATE END_DATE BAND_TYPE FLAG_LINE
3 1 01/03/2013 31/03/2013 R 1
4 1 01/03/2013 31/03/2013 R 0
5 2 01/03/2013 31/03/2013 R 1
6 2 01/03/2013 31/03/2013 R 0
7 3 01/03/2013 31/03/2013 R 0
8 3 01/03/2013 31/03/2013 N 0
我试着分块进行:即为每个范围运行类似的程序:
ID RANGE_ID START_DATE END_DATE BAND_TYPE FLAG_LINE
3 1 01/03/2013 31/03/2013 R 1
5 2 01/03/2013 31/03/2013 R 1
7 3 01/03/2013 31/03/2013 R 0
8 3 01/03/2013 31/03/2013 N 0
对于每个范围使用此方法,我填充一个临时表,并在最后返回结果,但这不是很灵活,是否有其他方法可以实现
谢谢像这样试试
begin
for x in ( select count(*) cnt
from dual
where exists (
select 1 FROM myTable
WHERE RANGE_ID = 1 AND FLAG_LINE = 1) )
loop
if ( x.cnt = 1 )
then
dbms_output.put_line('flag line exists');
--insert the line with FLAG_LINE = 1 into temp table for this range
else
dbms_output.put_line('does not exist');
--insert the lines into temp table for this range
end if;
end loop;
end;
像这样试试
begin
for x in ( select count(*) cnt
from dual
where exists (
select 1 FROM myTable
WHERE RANGE_ID = 1 AND FLAG_LINE = 1) )
loop
if ( x.cnt = 1 )
then
dbms_output.put_line('flag line exists');
--insert the line with FLAG_LINE = 1 into temp table for this range
else
dbms_output.put_line('does not exist');
--insert the lines into temp table for this range
end if;
end loop;
end;
试试这个
Select * from tablename where flag=1
union
(Select * from tablename a where (Select count(*) from tablename b
where a.Range_id=b.RANGE_ID and b.flag=1)<1)
试试这个
Select * from tablename where flag=1
union
(Select * from tablename a where (Select count(*) from tablename b
where a.Range_id=b.RANGE_ID and b.flag=1)<1)
这里有另一种方法可以得到你想要的结果
select * from myTable
where flag_line = 1
or
(range_id, start_date, end_date, band_type) in (
select range_id, start_date, end_date, band_type
from myTable
group by range_id, start_date, end_date, band_type
having max(flag_line) = 0)
这里有另一种方法可以得到你想要的结果
select * from myTable
where flag_line = 1
or
(range_id, start_date, end_date, band_type) in (
select range_id, start_date, end_date, band_type
from myTable
group by range_id, start_date, end_date, band_type
having max(flag_line) = 0)