1

我写了一个sql查询

select a.unit_code unit,
       a.gh_vill pl_vill,
       a.gh_grow pl_grow,
      (select gh_area 
         from w_cane_survey_2013 b 
        where b.croptype_code > 12 and a.gh_no = b.gh_no ) as paudha,
      (select gh_area 
         from w_cane_survey_2013 b
        where b.croptype_code < 13 and a.gh_no = b.gh_no) as pedi 
  from w_cane_survey_2013 a 
 where a.unit_code = '03' and a.gh_vill = '9991' and gh_grow = '1';

当我执行它时出现错误

ORA-01427: 单行子查询返回多于一行
01427. 00000 - “单行子查询返回多于一行”
*原因:
*操作:

4

4 回答 4

2

这是因为子查询返回多行。在子查询中再增加一个 ROWNUM=1 的条件试试。

select 
    a.unit_code unit, 
    a.gh_vill pl_vill, 
    a.gh_grow pl_grow, 
    (select gh_area from w_cane_survey_2013 b 
      where b.croptype_code > 12 and a.gh_no = b.gh_no and ROWNUM=1) as paudha, 
    (select gh_area from w_cane_survey_2013 b 
      where b.croptype_code < 13 and a.gh_no = b.gh_no and ROWNUM=1) as pedi 
from 
    w_cane_survey_2013 a 
where 
    a.unit_code = '03' and 
    a.gh_vill = '9991' and 
    gh_grow = '1';
于 2013-10-07T11:45:06.133 回答
1

试试这个查询,我希望它会有所帮助:

select unit_code as unit,
   gh_vill as pl_vill,
   gh_grow as pl_grow,
   case when croptype_code > 12 then gh_area end as paudha,
   case when croptype_code < 13 then gh_area end as pedi
from 
w_cane_survey_2013 
where 
unit_code = '03' and gh_vill = '9991' and gh_grow = '1' 
Group by
unit_code, gh_vill , gh_grow, croptype_code, gh_area;
于 2013-10-07T13:04:06.520 回答
1

很明显,您获取的数据不止一行。请查看您的表格或做更多的限制,以便您只能获取一行。

于 2013-10-07T11:51:17.567 回答
0
select distinct 
a.unit_code unit, a.gh_vill pl_vill, a.gh_grow pl_grow, a.gh_srno,
nvl((select gh_area 
     from w_cane_survey_2013 b 
     where b.croptype_code > 12 and a.gh_srno = b.gh_srno ),0) as paudha,
nvl((select gh_area 
     from w_cane_survey_2013 b 
     where b.croptype_code < 13 and a.gh_srno = b.gh_srno),0) as pedi
from w_cane_survey_2013 a
where a.unit_code = '03' and a.gh_vill = '9991' and gh_grow = '1';

我使用了 distinct,因为如果我在子查询中使用rownum = 1,那么即使这个组合有 16 行,它也只返回一行,而且正如@user2780501 回答的那样,我做同样的事情。

现在我使用上面的查询得到了正确的记录。

于 2013-10-07T12:12:01.253 回答