在单个 oracle 查询中获取行数和其他列值

Posted

技术标签:

【中文标题】在单个 oracle 查询中获取行数和其他列值【英文标题】:Fetch number of rows and other column value in single oracle query 【发布时间】:2021-10-19 14:46:58 【问题描述】:

考虑一下我有下面的表,分别称为 Book_detail 和 Author_detail:

Id BookId Name
1 1001 ABC
2 2001 XYZ
Price BookId Name
100 1001 Sham
200 2001 Ram

我想要以下结果:

countA countB id
1 1 2

我在下面尝试但没有工作:

Select (select count(*) from Author_Detail where BookId = 2001) as countA,
       (select count(*) as countB, Id as id from Book_Detail where BookId = 2 group by Id) 
from dual;

【问题讨论】:

【参考方案1】:

使用您发布的示例数据:

SQL> with
  2  book_detail (id, bookid, name) as
  3    (select 1, 1001, 'ABC' from dual union all
  4     select 2, 2001, 'XYZ' from dual
  5    ),
  6  author_detail (price, bookid, name) as
  7    (select 100, 1001, 'Sham' from dual union all
  8     select 200, 2001, 'Ram'  from dual union all
  9     select 300, 3001, 'xxx'  from dual
 10    )
 11  select count(a.bookid) counta,
 12         count(distinct b.id) countb,
 13         b.id
 14  from book_detail b join author_detail a on a.bookid = b.bookid
 15  where a.bookid = 2001
 16  group by b.id;

    COUNTA     COUNTB         ID
---------- ---------- ----------
         1          1          2

SQL>

【讨论】:

以上是关于在单个 oracle 查询中获取行数和其他列值的主要内容,如果未能解决你的问题,请参考以下文章

VBA中如何获取一个表格的行数和列数

获取 oracle db 中的所有视图以及行数、列数、主键等详细信息

如何获取ResultSet的行数和列数

Java获得数据库查询结果的列数和行数,打印查询结果

查询所有HIVE表分区数据量

查询所有HIVE表分区数据量