sum(c1)* sum(c2)和sum(c1 * c2)之间的SQL不同

时间:2017-06-15 22:02:56

标签: sql

在SQL语言中,

之间的结果或性能有何不同
sum(c1) * sum(c2) from t

sum(c1 * c2) from t

我用它来计算销售总额

select sum(price * quantity) as total from Bill

那么什么是最佳选择?

3 个答案:

答案 0 :(得分:2)

垂直和水平求和......假设没有NULLS

declare @mytable table (a int, b int)

insert into @mytable 
values 
(1,1),
(2,3)


select * from @mytable

select sum(a) * sum(b) from @mytable  -- result is 12 .. vertical/column, summarize column first then multiply to other column

select sum(a*b) from @mytable  --- result is 7  .. horizontal/row, summarize the product of a and b

答案 1 :(得分:1)

这不是SQL的问题。这只是基本的数学。假设c1 =(0,1)且c2 =(2,3)。然后:

sum(c1)*sum(c2) alias... (0+1)*(2+3) = 5

与:

相同
sum(c1*c2)      alias... (0*2)+(1*3) = 3

答案 2 :(得分:0)

NULL和零是一个问题

Declare @YourTable table (C1 money,C2 money)
Insert Into @YourTable values
 (100,10)
,(100,null)

Select sum(c1) * sum(c2)   -- 2000.00
 From @YourTable

Select sum(c1 * c2)        -- 1000.00
 From @YourTable