不同的SQL-返回单行

时间:2018-10-20 06:43:40

标签: sql oracle

我有一个包含以下记录的表:

Column A   Column B

1           XX
2           XX
3           XX
4           XX

如何仅使用ColumnB而不显示ColumnA来显示 1条记录。 就像我应该说的

select from Table T where ColumnB ='XX'

,只有 1行应该返回。

5 个答案:

答案 0 :(得分:1)

您可以使用以下之一:

with t(colA,ColB) as
(  
 select 1,'XX' from dual union all
 select 2,'XX' from dual union all
 select 3,'XX' from dual union all
 select 4,'XX' from dual    
)
select ColB 
  from t
 where ColumnB = 'XX' and rownum = 1;

select ColB from
(
    with t(colA,ColB) as
    (  
     select 1,'XX' from dual union all
     select 2,'XX' from dual union all
     select 3,'XX' from dual union all
     select 4,'XX' from dual    
    )
    select ColB,
           row_number() over (order by ColB) as rn
      from t
)
where ColumnB = 'XX' and rn=1;

或者如果您的数据库版本为12c,则该版本也可以:

with t(colA,ColB) as
(  
 select 1,'XX' from dual union all
 select 2,'XX' from dual union all
 select 3,'XX' from dual union all
 select 4,'XX' from dual    
)
select ColB 
from t
where ColumnB ='XX'
fetch {first|next} 1 {row|rows} only;

应优先选择关键字firstnextrowrows中的一个。

答案 1 :(得分:1)

如果您真的不在乎返回哪个匹配记录,则使用rownum伪列:

select * from Table T where ColumnB ='XX' 
and rownum = 1;

此查询仅返回结果集中的第一行。这是获得一行的最便宜的方法。结果是不确定的,因为没有排序顺序,并且不可能:rownum与ORDER BY配合不好,这就是为什么您不关心返回哪一行很重要的原因。

答案 2 :(得分:0)

您可以这样做

select from Table T where ColumnB ='XX' group by ColunmB

答案 3 :(得分:0)

由于您实际上并不在意返回哪个a,所以

SQL> with test (a, b) as
  2  (select 1, 'xx' from dual union all
  3   select 2, 'xx' from dual union all
  4   select 3, 'yy' from dual
  5  )
  6  select min(a) a, min(b) b
  7  from test
  8  where b = 'xx';

         A B
---------- --
         1 xx

SQL>

答案 4 :(得分:0)

感谢大家的想法。

我尝试了以下方法,并且对我有用

从tale_name中选择a.column_name        排在哪里(                        选择RID FROM                         (                           SELECT ROWID RID,ROW_NUMBER()OVER(按a.column_name排序,按ROWID排序)RN                           FROM table_name一个where column_name在                              (从diff_table_name中选择TO_CHAR(column_name))                         )RN = 1