2011-08-25 4 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 table 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 개가 있습니다. 각 OS는 데이터베이스 당 한 번 두 번 나열됩니다.

저는 Google과 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의 올바른 조합을 파악하지 못했습니다. 다시 고마워! –