我有两个SELECT查询。是否可以合并它们并获得我想要的结果?

时间:2014-11-20 17:40:37

标签: sql oracle

我有两个SELECT查询,第一个是如下:

SELECT u.Table_Name AS Tables, COUNT(*) AS ColumnCount
FROM User_Tab_Columns u
GROUP BY u.Table_Name;

这给了我:

TABLES                         COLUMNCOUNT
------------------------------ -----------
DEPT                                     3
DUMMY                                    1
EMP                                      8
BONUS                                    4
SALGRADE                                 3

第二个问题:

SELECT 'Emp' AS Tables, COUNT(*) AS RowCount FROM Emp
UNION
SELECT 'Dept', COUNT(*) FROM Dept
UNION
SELECT 'Salgrade', COUNT(*) FROM Salgrade
UNION
SELECT 'Dummy', COUNT(*) FROM Dummy
UNION
SELECT 'Bonus', COUNT(*) FROM Bonus;

这给了我:

TABLES     ROWCOUNT
-------- ----------
Bonus             0
Dept              4
Dummy             1
Emp              14
Salgrade          5

我需要帮助编写一个查询,它会给我一些如下所示的内容:

TABLES   COLUMNCOUNT ROWCOUNT
-------- ----------- --------
Bonus              4        0
Dept               3        4
Dummy              1        1
Emp                8       14
Salgrade           3        5

我完全陷入困境。如果有人能告诉我正确的道路,那就太棒了。

2 个答案:

答案 0 :(得分:2)

试试这个。

SELECT a.Tables,
       ColumnCount,
       ROWCOUNT
FROM   (SELECT u.Table_Name AS Tables,
               Count(*)     AS ColumnCount
        FROM   User_Tab_Columns u
        GROUP  BY u.Table_Name) A
       JOIN (SELECT 'Emp'    AS Tables,Count(*) AS ROWCOUNT
             FROM   Emp
             UNION
             SELECT 'Dept',Count(*)
             FROM   Dept
             UNION
             SELECT 'Salgrade', Count(*)
             FROM   Salgrade
             UNION
             SELECT 'Dummy',Count(*)
             FROM   Dummy
             UNION
             SELECT 'Bonus',Count(*)
             FROM   Bonus) B
         ON lower(a.Tables) = lower(b.Tables) 

答案 1 :(得分:0)

在Oracle中,您可以使用"使用" select中的关键字并在查询中使用它 所以在你的情况下:

WITH 
tempTable1 AS
  ( SELECT u.Table_Name AS Tables, COUNT(*) AS ColumnCount
   FROM User_Tab_Columns u
   GROUP BY u.Table_Name),
tempTable2 AS
  (SELECT 'Emp' AS Tables,
          COUNT(*) AS RowCount
   FROM Emp
   UNION SELECT 'Dept', COUNT(*)
   FROM Dept
   UNION SELECT 'Salgrade', COUNT(*)
   FROM Salgrade
   UNION SELECT 'Dummy', COUNT(*)
   FROM Dummy
   UNION SELECT 'Bonus', COUNT(*)
   FROM Bonus)
SELECT *
FROM tempTable1,
     tempTable2
WHERE tempTable1.tables = tempTable2.tables;

我现在无法访问Oracle数据库来检查语法和输出,但这应该会给您一个基本的想法。您可以找到更多信息here