我正在运行第一个查询以获取总计,然后将这些总计存储在两个名为 @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