2011-08-25 124 views
1

我有一個查詢,它針對每個操作系統提供計算機的總數,程序XYZ的總數,免除需要程序XYZ的總數以及程序XYZ的總數(這是所有那些沒有XYZ程序並且沒有豁免的人)。我的數據位於兩個表格中,我希望可以使用聯合將數據合併爲單個結果。這裏是我的意思:用於多列查詢的SQL COUNT UNION

SELECT [OS Name], 
(SELECT COUNT (DISTINCT statement for total computers including a few joins and where)) 
(SELECT COUNT (DISTINCT statement for installed including a few joins and where)) 
(SELECT COUNT (DISTINCT statement for exempt including a few joins and where)) 
(SELECT COUNT (DISTINCT statement for missing including a few joins and where and a subquery)) 
FROM table 

我可以發佈真正的查詢,如果它是有幫助的。每個SELECT都是SELECT COUNT(DISTINCT Guid)FROM表JOIN table2 JOIN table3 WHERE condition1和condition2,其中一些使用WHERE語句中的子查詢。

它返回的結果是這樣的:

OS Name Total computers for this OS Program Installed Exempt Missing Program 
Microsoft Windows XP 4776 819 12 3955 
Windows 7 Enterprise 4 1 1 2 

第二運行查詢不同的數據庫:

OS Name Total computers for this OS Program Installed Exempt Missing Program 
Microsoft Windows XP 42 7 0 36 
Windows 7 Enterprise 2196 2143 21 33 

我的希望是,簡單地把兩個之間的聯盟將加起來的數量和我的數據將有兩行,但它有4個 - 每個操作系統列出兩次,每個數據庫一次。

我已經搜索谷歌和Stackoverflow,沒有運氣。

線程這樣SQL Count(*) on multiple tablestwo SQL COUNT() queries?似乎是正確的做法,但我掙扎,滿腦子都在,我怎麼能使用它,因爲我的計數複雜。對於簡單的列名不是COUNT(emp_id),而是使用JOIN,條件,有時候是子查詢。

+0

真正的查詢將是有用的 –

回答

1

使用你的聯合,但你需要根據這些結果進一步聚合。查詢近似。

SELECT 
    D.[OS Name] 
, SUM(D.[Computer Count]) AS [Computer Count] 
, D. ... 
FROM 
(
SELECT [OS Name], 
(SELECT COUNT (DISTINCT statement for total computers including a few joins and where)) 
(SELECT COUNT (DISTINCT statement for installed including a few joins and where)) 
(SELECT COUNT (DISTINCT statement for exempt including a few joins and where)) 
(SELECT COUNT (DISTINCT statement for missing including a few joins and where and a subquery)) 
FROM table 

UNION ALL 
SELECT [OS Name], 
(SELECT COUNT (DISTINCT statement for total computers including a few joins and where)) 
(SELECT COUNT (DISTINCT statement for installed including a few joins and where)) 
(SELECT COUNT (DISTINCT statement for exempt including a few joins and where)) 
(SELECT COUNT (DISTINCT statement for missing including a few joins and where and a subquery)) 
FROM table2 
) D 
GROUP BY 
    D.[OS Name] 
+0

哇,我的頭撞了幾個小時。謝謝!我試圖做一個類似的安排,通過使它們進行子查詢,但我只是沒有找出SUM,UNION和GROUP BY的正確組合。再次,謝謝! –