如何从同一 select 语句中求和另一个总和的值

How to sum the value of another sum from same select statement

我正在尝试在同一 select 语句中对另一个总和的值求和,然后我想检查 case 语句中的总和值。当我这样做时,它正在工作,而不是它只是获得个人价值。

我必须对 Billable_Trades 求和,然后如果 billable_trades 高于某些数字,我必须给出一些费率,我需要知道 billable_trade 的总数。

select t.Business_Unit_Description, -- case when Product_Type_Description = 'Fee Based' then 'Fee Based' else '' end as revenue_type,
              billable_trades,
              isnull(c.comm_adjustments, 0) as commission_adjustments,
              rate,
              billable_trades*rate as charges,
              0.3 as commission_rate,
              isnull(c.comm_adjustments, 0)*0.3 as credit,
              (billable_trades*rate)- isnull(c.comm_adjustments, 0)*0.3 as total
            from   
       (
       select Business_Unit_Description,
        sum(billable_trades) as billable_trades, 
        CASE WHEN SUM(billable_trades) > 0 and SUM(billable_trades) <= 150000 THEN 0.85667 ELSE 0.47104 END as rate
      from   cte_combined
       group by Business_Unit_Description
       ) t
       left outer join cte_comm_adj c on c.Business_Unit_Description = t.Business_Unit_Description
order by t.Business_Unit_Description

查询的内容显然比显示的要多 - 因为您正在使用派生的 table 来引用 CTE 以及外部连接到另一个 CTE。

我会将利率的计算移出派生的 table:

Select t.Business_Unit_Description -- case when Product_Type_Description = 'Fee Based' then 'Fee Based' else '' end as revenue_type,
     , t.sum_billable_trades
     , commission_adjustments = isnull(c.comm_adjustments, 0)
     , r.rate
     , charges                = t.sum_billable_trades * r.rate
     , commission_rate        = 0.3
     , credit                 = isnull(c.comm_adjustments, 0) * 0.3
     , total                  = (t.sum_billable_trades * r.rate) - isnull(c.comm_adjustments, 0) * 0.3
  From (Select Business_Unit_Description
             , sum_billable_trades = sum(billable_trades)
          From cte_combined
         Group By Business_Unit_Description) t
  Cross Apply (Values (iif(t.sum_billable_trades > 0 And t.sum_billable_trades <= 150000, 0.85667,  0.47104))) As r(rate)
  Left Outer Join cte_comm_adj               c On c.Business_Unit_Description = t.Business_Unit_Description
 Order By t.Business_Unit_Description;

我也不会对总和使用相同的名称只是为了更清楚。