2015-07-20 129 views
0

我有兩個查詢。一個用於分子,另一個用於分母。如何組合這兩個查詢,以便我的結果是一個包含分子,分母和分組的表格?期望輸出的結合兩個查詢來獲取分子,分母和分組

Query and results

例子:

Numerator | Denominator | Grouping 
----------|-------------|--------- 
30  | 51   | 1111 
172  | 216   | 2768 
+0

請不要發佈SQL語句或示例數據作爲屏幕截圖。改爲發佈格式化測試。 SQL甚至不可讀。 –

回答

0

你真的在同一個表中的兩個不同的聚合。出於很多原因,性能就是其中之一,您不希望將查詢分解爲兩部分,然後重新將它們連接在一起。你可以完成通過使用列級過濾,而不是WHERE子句篩選正確的結果:

select [officerID] 
    ,sum(case when [ST3ID] != '' then 1 else 0 end) as [Numerator] 
    ,count(*) as [Denomimator] 
FROM [dbo].[cobanVideos] 
WHERE [starting] > '6/1/2015 0:00:00 AM' 
AND [starting] < '7/1/2015 0:00:00 AM' 
GROUP BY [officerID] 

通過使用CASE語句來過濾在列級的數據,可以同時獲取這兩個值。您還可以通過加入以下作爲附加列計算百分比值(分子/ denminator):

select [officerID] 
    ,sum(case when [ST3ID] != '' then 1 else 0 end) as [Numerator] 
    ,count(*) as [Denomimator] 
    ,case when count(*) <> 0 
      then sum(case when [ST3ID] != '' then 1.0 else 0 end)/count(*) 
      else 0 
     end as [Pct ST3] 
FROM [dbo].[cobanVideos] 
WHERE [starting] > '6/1/2015 0:00:00 AM' 
AND [starting] < '7/1/2015 0:00:00 AM' 
GROUP BY [officerID] 

SQL窗口功能,給你一個整體的其他的工具集,用於在不同層次聚集的聚集工作,所有在一個查詢中。如果你有興趣,我可以跟進一個例子,說明你如何計算每位軍官的軍官比例,並且確定每個軍官對總數的貢獻百分比,所有這些都用一個SELECT。

0

使用JOIN:

Select numerator.Count, denominator.Count, numerator.officerID from (SELECT COUNT() as Count, officerID FROM [dbo].[cobanVideos] WHERE starting > '6/1/2015 0:00:00 AM' AND starting < '7/1/2015 0:00:00 AM' AND ST3ID != '' GROUP BY officerID) numerator Join (SELECT COUNT() as Count, officerID FROM [dbo].[cobanVideos] WHERE starting > '6/1/2015 0:00:00 AM' AND starting < '7/1/2015 0:00:00 AM' GROUP BY officerID) denominator On numerator.officerId = denominator.officerId 
+0

我試過了:'選擇*從 (SELECT COUNT(*),officerID \t FROM [dbo]。[cobanVideos] WHERE starting>'6/1/2015 0:00:00 AM'AND starting <'7/1/2015 0:00:00 AM'ST3ID!=''GROUP BY officerID)分子 加入 (SELECT COUNT(*),officerID \t FROM [dbo]。[cobanVideos] WHERE starting>'6/1/2015 0:00:00 AM'開始<'7/1/2015 0:00:00 AM'GROUP BY officerID)分母 On numerator.officerId = denominator.officerId'並且沒有列名被指定爲'分子'。 消息:8155,級別:16,狀態:2,過程:,行:4 –

+0

您必須命名子選擇中的列。 請參閱我的編輯 – TheJoeIaut

0

對於你的結果想,你必須使用一個案例Statment

這裏是例子

SELECT 
SUM(CASE WHEN ST3ID != '' THEN 1 ELSE 0 END) [NUMERATOR] , 
COUNT(*)          [DENOMINATOR], 
officerID          [GROUPING] 
FROM [dbo].[cobanVideos] 
WHERE [starting] > '6/1/2015 0:00:00 AM' 
AND [starting] < '7/1/2015 0:00:00 AM' 
GROUP BY GROUPINGID 

爲了回答你的問題,你必須使用一個加入statment

例子:

SELECT 
    ISNULL(numerator,0)    as [Numerator], 
    ISNULL(Denominator,0)   as [Denominator], 
    ISNULL(a.officerID,b.officerID) as [Grouping] 
FROM 
(SELECT COUNT(*) numerator, officerID ....) AS [TableA] 
FULL JOIN 
(SELECT COUNT(*) Denominator, officerID ....) AS [TableB] 
ON [TableA].[officerID] = [TableB].[officerID]