无法对列值求和

时间:2014-05-02 14:17:20

标签: sql sql-server sql-server-2008

我使用以下查询来汇总我的列值。

查询:

select 
'$ ' + REPLACE( CONVERT(VARCHAR(32),cast(round(isnull(sum([Share_Invest]),0),0)as     MONEY),1), '.00', '') [Investment], 
'$ ' + REPLACE( CONVERT(VARCHAR(32),cast(round(isnull(sum([Profit_Share]),0),0)as MONEY),1), '.00', '') [Profit Amount],
[Variance] = '$ ' + REPLACE( CONVERT(VARCHAR(32),cast(round(isnull(sum([Share_Invest]-[Profit_Share]),0),0)as MONEY),1), '.00', '') 
from Finance

对于第一列,它的罚款和总和正在显示。但我的Profit_Share列也有空值和数据,这并不是对列值进行求和。

任何人都可以在我出错的地方纠正我。

1 个答案:

答案 0 :(得分:1)

您的查询没有错,
但如果[Share_Invest]或[Profit_Share]值为小数($ 50.05,$ 10.10),你可能会遇到麻烦

承担@finance表是您的财务表:

 declare @finance table
(
 id int identity,
 [Share_Invest] money,
 [Profit_Share] money
)


insert into @finance
select '50.05', '10.00' union all
select '20.05', '5.00' union all
select null, '5.00' union all
select null, null union all
select '10.00', null union all
select null, null

-- your query
select 
'$ ' + REPLACE( CONVERT(VARCHAR(5),cast(round(isnull(sum([Share_Invest]),0),0)as     MONEY),1), '.00', '') [Investment], 
'$ ' + REPLACE( CONVERT(VARCHAR(5),cast(round(isnull(sum([Profit_Share]),0),0)as MONEY),1), '.00', '') [Profit Amount],
[Variance] = '$ ' + REPLACE( CONVERT(VARCHAR(5),cast(round(isnull(sum([Share_Invest]-[Profit_Share]),0),0)as MONEY),1), '.00', '') 
from @Finance

/*
Investment Profit Amount Variance
---------- ------------- ---------
$ 80       $ 20          $ 60
*/

-- modified query
select
'$ ' + cast(sum(isnull([Share_invest],0)) as nvarchar(5))  as [Investment]
,'$ ' + cast(sum(isnull([Profit_Share],0)) as nvarchar(5))  as [Profit Amount]
, '$ ' + cast(sum(isnull([Share_invest],0) - isnull([Profit_Share],0)) as nvarchar(max)) as [Variance]
from @finance

/*
Investment Profit Amount Variance
---------- ------------- ---------
$ 80.10    $ 20.00       $ 60.10
*/

我删除了演员阵容(如钱)和圆形