2014-11-20 26 views
0

我有兩個SELECT查詢,首先如下:我有兩個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

試試這個。

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) 
+0

感謝您的答覆。我收到以下消息:'[ROWCOUNT] * 錯誤在第3行: ORA-00936:缺少表達式 – ShaunKelly01 2014-11-20 17:52:08

+0

@ ShaunKelly01 - 現在檢查 – 2014-11-20 17:53:07

+0

'無行選擇'是我給。 – ShaunKelly01 2014-11-20 18:03:33

0

在Oracle中你可以使用「與」在選擇關鍵字,所以你的情況用它查詢 :

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

+0

感謝您的回答。我輸入了你的查詢,但是它回來了:'ERROR at line 1:'ERROR at line 1: ORA-00903:invalid table name' – ShaunKelly01 2014-11-20 18:05:38

+0

@ ShaunKelly01我從內存中寫了查詢,所以可能是語法錯誤。你看過答案中的鏈接嗎?本質上是通過以下方式使用: 'WITH subquery_name AS (聚集的SQL語句) 選擇 (查詢命名subquery_name);' – dubes 2014-11-20 18:08:54

+1

的'('立即WITH'和匹配''後)'後需要刪除。 – 2014-11-20 18:09:34

相關問題