SQL Server 2008R2 - 如何显示组中计算列的两行之间的差异?

SQL Server 2008R2 - How to show difference between two rows of a calculated column in a group?

我是 SQL 服务器的新手,很难想出解决方案。我的查询按地区和种族汇总了离开者和成功者的总数,将成功者除以离开者得到成功率。我想展示每个区域分组中英国白人和 BME 的成功率之间的差异。我的计划是使用这个值来突出显示种族之间的差异大于(例如)5% 的区域。

查询的数据源是一个 excel sheet 约 20,000 行

SELECT 
[AssDir Name] AS Area, 
Ethnicity2 AS Ethnicity, 
SUM([Leavers Overall]) AS Leavers,  
SUM([Ach Overall]) AS Achievers, 
SUM([Ach Overall]) / NULLIF (SUM([Leavers Overall]), 0) * 100 AS Success

FROM Sheet1$

GROUP BY [AssDir Name], Ethnicity2
ORDER BY [AssDir Name], 
CASE WHEN [Ethnicity2]='White British' THEN '1' ELSE [Ethnicity2] END

它像这样生成前五列 - 我希望能够添加差异列:

    Area    Ethnicity       Leavers Achievers   Success      Difference
    ====================================================================        
    ABC     White British   325     253         77.84615385  3.234927235
    ABC     BME             111     90          81.08108108  3.234927235
    ABC     Not Provided    7       5           71.42857143  3.234927235
    DEF     White British   291     196         67.35395189  -13.11666375
    DEF     BME             59      32          54.23728814  -13.11666375
    DEF     Not Provided    1       1           100          -13.11666375
    GHI     White British   684     578         84.50292398  4.487901711
    GHI     BME             109     97          88.99082569  4.487901711
    GHI     Not Provided    2       2           100          4.487901711

让它在引起头痛的组中工作 - 这对所有区域都适用,但我看不到一种方法来调整它,以便在区域是分组列时它可以工作:

SELECT 

Ethnicity2 AS Ethnicity, 
SUM([Leavers Overall]) AS Leavers, 
SUM([Completed Overall]) AS Completers, 
SUM([Ach Overall]) AS Achievers, 
SUM([Ach Overall]) / NULLIF (SUM([Leavers Overall]), 0) * 100 AS Success,
(SELECT 
        SUM([Ach Overall]) / NULLIF (SUM([Leavers Overall]), 0) * 100 
        FROM Sheet1$ 
        WHERE Ethnicity2 = 'BME'
        GROUP BY  Ethnicity2)
- (SELECT 
        SUM([Ach Overall]) / NULLIF (SUM([Leavers Overall]), 0) * 100 
        FROM Sheet1$ 
        WHERE Ethnicity2 = 'White British'
        GROUP BY  Ethnicity2) AS Diff

FROM Sheet1$
GROUP BY  Ethnicity2 

抱歉,篇幅太长了,希望有一个我遗漏的优雅解决方案,但是 googling/searching 的几个小时却一片空白。

没有任何花哨的快速破解:

with q as (
    SELECT 
    [AssDir Name] AS Area, 
    Ethnicity2 AS Ethnicity, 
    SUM([Leavers Overall]) AS Leavers,  
    SUM([Ach Overall]) AS Achievers, 
    SUM([Ach Overall]) / NULLIF (SUM([Leavers Overall]), 0) * 100 AS Success
    FROM Sheet1$
    GROUP BY [AssDir Name], Ethnicity2
)
select
    Area, Ethnicity, Leavers, Achievers, Success,
    (select Success from q q2 where q2.Area = q.Area and q2.Ethnicity = 'BME') -
    (select Success from q q2 where q2.Area = q.Area and q2.Ethnicity = 'White British') as Difference
from q
ORDER BY Area, 
CASE WHEN Ethnicity ='White British' THEN '1' ELSE Ethnicity END

如果您将内部查询与外部区域相关联,您的方法可能会奏效。