2011-08-25 122 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的正确组合。再次,谢谢! –