分隔行中的平均结果

时间:2016-05-13 11:06:57

标签: tsql

是否可以使用单列的平均结果获得额外的行?

示例:

enter image description here

2 个答案:

答案 0 :(得分:0)

我唯一能想到的是这样的事情:

with mainCte as (
    SELECT 
        DetailID, Quantity, Value      
    FROM 
        dbo.Detail
),
rowCte as (
    SELECT 
        sumQuantity = sum(Quantity), 
        avgValue = avg(Value)    
    FROM 
        dbo.Detail 
)
select 
    DetailID,
    Quantity,
    Value 
from 
    mainCte

union

select
    DetailID = null,
    Quantity = sumQuantity,
    Value = avgValue
from
    rowCte

答案 1 :(得分:0)

有两种解决方案。

1)with rollup - 汇总将执行通常的分组,加上汇总到它上面可能的每个级别。虽然这是一个很好的解决方案,但我相信微软已经表示它很快就会被弃用。

2)grouping sets - 这是新的汇总解决方案,您可以在其中指定汇总的每个级别,其中包括()的分组集将汇总到最高级别。< / p>

我个人更喜欢选项2,所以我在答案中使用了那个。

请参阅下面的解决方案:

create table ##tmp_tbl_main
    (
        customer int not null
        , recv_weight decimal(10,2) not null
        , rej_weight decimal(10,2) not null
    )

insert into ##tmp_tbl_main values (1,100.00,5.00)
insert into ##tmp_tbl_main values (2,120.00,4.00)
insert into ##tmp_tbl_main values (3,230.00,20.00)
insert into ##tmp_tbl_main values (4,120.00,10.00)
insert into ##tmp_tbl_main values (5,50.00,3.00)


select coalesce(cast(a.customer as varchar(10)), 'Total') as Customer
, sum(a.recv_weight) as [Received Weight]
, format(avg(a.rej_weight), '0.00') as [Rejected Weight]
, format(case when a.customer is NULL or sum(a.recv_weight) = 0 then NULL --protecting against div/0 error
       else sum(a.rej_weight)/sum(a.recv_weight)
  end, '0.00%') as [% Rejected]
from ##tmp_tbl_main as a
group by grouping sets
    (
        (a.customer)
        , ()
    )

<强>结果:

groupingSetsResults