如何从多个列中汇总一列

时间:2015-01-14 07:44:20

标签: sql-server tsql sql-server-2008-r2

有表格:

DECLARE @tbl TABLE (a1 varchar(50),b1 money,c1 money,d1 money)

INSERT INTO @tbl (a1,b1,c1,d1)
values('test1',5,14.00,13.00),('test1',5,10.00,3.00),('test3',2,8.00,4.00)

a1       b1       c1    d1     
test1   5.00    10.00   3.00    
test1   5.00    14.00   13.00   
test3   2.00    8.00    4.00

想要和d1列然后需要像sum_d1列* 0.18这样的新列,需要类似的东西:

select a1,b1,c1,d1,SUM(d1) as [d1_sum],[d1_sum] * 0.18 as [kpv],[d1_sum] + [kpv] as [new_sum]
from @tbl 
GROUP BY a1,b1,c1,d1

怎么做?

编辑: 回应必须如下:

 a1      b1       c1    d1     d1_sum   kpv  new_sum
test1   5.00    10.00   3.00    20.00   3.6    23.6
test1   5.00    14.00   13.00   20.00   3.6    23.6 
test3   2.00    8.00    4.00    20.00   3.6    23.6

1 个答案:

答案 0 :(得分:4)

您可以使用SUM OVER()

SELECT
    a1,
    b1,
    c1,
    d1,
    SUM(d1) OVER (PARTITION BY(SELECT NULL)) AS d1_sum,
    SUM(d1) OVER (PARTITION BY(SELECT NULL)) * 0.18 AS kpv,
    SUM(d1) OVER (PARTITION BY(SELECT NULL)) + (SUM(d1) OVER (PARTITION BY(SELECT NULL)) * 0.18) AS new_sum
FROM @tbl

CROSS APPLY

SELECT
    t.a1, 
    t.b1, 
    t.c1, 
    t.d1,
    x.d1_sum,
    x.d1_sum * 0.18 AS kpv,
    (x.d1_sum * 0.18) + x.d1_sum AS new_sum
FROM @tbl t
CROSS APPLY(
    SELECT SUM(d1) as d1_sum FROM @tbl
) x