如何对多个列中的一列求和
How to sum one column from multiple
有 table 个赞:
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
您可以使用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
有 table 个赞:
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
您可以使用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