2016-02-11 23 views
0

我有一個查詢理應有這樣的輸出:我應該使用全部加入這個多數據庫SQL Server查詢

enter image description here

這裏是我的查詢:

select 
    table4.categoryNames, -- because only table4 has all the categories 
    table1.countResult, -- either (DATA) or null 
    table2.countResult, 
    table3.countResult, 
    table4.countResult, 
    table5.countResult, 
    table6.countResult, 
    table7.countResult 
from 
    table1 
full join 
    table2 on table1.categoryNames = table2.CategoryNames 
full join 
    table3 on table2.categoryNames = table3.CategoryNames 
full join 
    table4 on table3.categoryNames = table4.CategoryNames 
full join 
    table5 on table4.categoryNames = table5.CategoryNames 
full join 
    table6 on table5.categoryNames = table6.CategoryNames 
full join 
    table7 on table6.categoryNames = table7.CategoryNames 

和每個countResult是一個查詢本身,按照表someTable的字段CategoryNames在其各自的數據庫中計數ID:

with table1 as 
(
    select 
     categroyName, count(ID) as countResult 
    from 
     database1.someTable 
    group by 
     categroyName), 
-- table2 from database2.someTable 
-- table3 from database3.someTable , and so on 

我希望有一個category表,但沒有。輸出不正確,因爲它顯示名爲NULL的第7個類別。

我是SQL新手,我只是想知道在這種情況下我應該使用什麼最好的join

+0

你需要一個「主類別」表,從您的SQL註釋似乎是'SELECT DISTINCT categoryNames FROM table4'。現在您只需將所有內容都加入到該主子表中即可。通過subtable我的意思是這樣定義的東西:'(SELECT DISTINCT categoryNames FROM table4)MySubtable'你可以在你的查詢中將該表引用爲MySubTable。 –

回答

0

我認爲union allgroup by可能是一個更好的方法。這裏的基本思想是:

select categoryName, 
     max(cr1), max(cr2), max(cr3), max(cr4), max(cr5), max(cr6), max(cr7) 
from ((select categoryName, countResults as cr1, NULL as cr2, NULL as cr3, 
       NULL as cr4, NULL as cr5, NULL as cr6, NULL as cr7 
     from table1 
    ) union all 
     (select categoryName, NULL as cr1, countResults as cr2, NULL as cr3, 
       NULL as cr4, NULL as cr5, NULL as cr6, NULL as cr7 
     from table2 
    ) union all 
     . . . 
    ) t 
group by categoryName; 

如果你在一個表中的所有類別,那麼另一種方法是使用left join

​​
+0

創建一個'categories'表,然後'left join'似乎是一個更簡單的解決方案。非常感謝你 –