组合两个查询以获得分子,分母和分组

时间:2015-07-20 20:48:15

标签: sql sql-server

我有两个问题。一个用于分子,一个用于分母。如何组合这两个查询,以便我的结果是一个包含分子,分母和分组的表?

Query and results

所需输出的示例:

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

3 个答案:

答案 0 :(得分:0)

使用加入:

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

答案 1 :(得分: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。

答案 2 :(得分:0)

对于您想要的结果,您必须使用案例陈述

以下是示例

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

对于您的答案,您必须使用加入法规

示例:

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]