不能使用变量中的值来计算总和?

时间:2013-04-26 12:07:14

标签: sql sql-server tsql

我正在运行第一个查询以获取总计,然后将这些总计存储在两个名为@total和@ots的变量中。我想稍后在另一个查询中使用这些变量来计算一些百分比值,但是如图所示,我在结果集中以零结尾。

create table #temp (
count int,
ots int
) 

insert into #temp
select
count(i.ID) as  'total count',
sum(mc.ots) as 'Imps'

from 
Profiles P 
INNER JOIN ProfileResults PR ON P.ID = PR.ProfileID
INNER JOIN Items i ON PR.ItemID = I.ID
inner join batches b on b.ID = i.BatchID
left outer join BatchActionHistory bah on b.ID=bah.batchid
inner join ItemOrganisations ito (nolock) on i.ID= ito.ItemID
inner join Lookup_MediaChannels mc on mc.id = i.MediaChannelID

where p.ID = 41 
and b.StatusID IN (6,7)
and bah.BatchActionID = 6
and i.StatusID = 2
and i.IsRelevant = 1


declare @total int 
declare @ots int 

select @total = sum(count) from #temp
select @ots =  sum(ots) from #temp

select c.Name, 
count(i.ID) as  'total count',
sum(mc.ots) as 'Imps',
sum(case when ito.rating <50 then 1 else 0 end) as 'unfav count',
sum(case when ito.Rating =50  then 1 else 0 end) as 'neu count',
sum(case when ito.Rating >50  then 1 else 0 end) as 'fav count',

(sum(case when ito.rating < 50 then 1.0 else 0.0 end) / count(i.ID) * 100) as 'unfav %',
(sum(case when ito.Rating =50  then 1.0 else 0.0 end) / count(i.ID) * 100) as 'neu %',
(sum(case when ito.Rating >50  then 1.0 else 0.0 end) / count(i.ID) * 100) as 'fav %',

CONVERT(decimal(4,2),avg(ito.Rating)) as 'Av Rating %',

----------------------------------------------------------------------------
--problem encountered here 
    CONVERT(decimal(4,2),(count(i.ID)/ @total * 100)) as '% Total ',
    CONVERT(decimal(4,2),(sum(mc.ots)/ @ots * 100 )) as '% Imps'
--------------------------------------------------------------------------- 


from 
Profiles P 
INNER JOIN ProfileResults PR ON P.ID = PR.ProfileID
INNER JOIN Items i ON PR.ItemID = I.ID
inner join batches b on b.ID = i.BatchID
left outer join BatchActionHistory bah on b.ID=bah.batchid
inner join Lookup_Countries c (nolock)on b.CountryID = c.ID
inner join ItemOrganisations ito (nolock) on i.ID= ito.ItemID
inner join Lookup_ItemStatus lis (nolock) on lis.ID = i.StatusID
inner join Lookup_BatchStatus lbs (nolock) on lbs.ID = b.StatusID
inner join Lookup_BatchTypes bt on bt.id = b.Typeid
inner join Lookup_MediaChannels mc on mc.id = i.MediaChannelID

where p.ID = 41 
and b.StatusID IN (6,7)
and bah.BatchActionID = 6
and i.StatusID = 2
and i.IsRelevant = 1

Group By c.Name

enter image description here

1 个答案:

答案 0 :(得分:3)

对于整数,SQL Server只进行整数除法。这将返回0:

DECLARE @sum INT = 99
DECLARE @total INT = 100

SELECT  CONVERT(decimal(4,2),(@sum / @total * 100))

您应首先转换为浮动/固定点类型然后除以:

DECLARE @sum INT = 99
DECLARE @total INT = 100

SELECT  CONVERT(decimal(4,2),(@sum * 100.00 / @total))

您还可以使用窗口功能:

SELECT  SUM(ms_otc) * 100.00 / SUM(SUM(ms_otc)) OVER () AS [% Imps],
        ...
FROM    Profiles P
        ...
GROUP BY
        c.name