用于多列查询的SQL COUNT UNION

时间:2011-08-25 20:03:40

标签: sql

我有一个查询,对于每个操作系统,它提供计算机的总数,程序XYZ的总数,不需要程序XYZ的总数,以及缺少程序XYZ的总数(这是所有没有的人程序XYZ并不是免税的)。我的数据在两个表中,我希望我可以使用联合将数据折叠成一个结果。这就是我的意思:

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

我希望简单地在这两者之间添加一个UNION会增加数字,我的数据将有两行,而是有4行 - 每个操作系统列出两次,每个数据库一次。

我搜索了Google和Stackoverflow,没有运气。

SQL Count(*) on multiple tables这样的线程 two SQL COUNT() queries?似乎是正确的方法,但由于我的COUNT很复杂,我正在努力解决如何使用它的问题。对于一个简单的列名,它不是COUNT(emp_id),而是使用JOIN,条件,有时是子查询。

1 个答案:

答案 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]
相关问题