0
我正在运行第一个查询以获取总计,然后将这些总计存储在名为@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
是否使用SQL服务器2012?如果是这样,您可以使用count(i.ID)over(by c.Name分区)/ count(i.ID)over()或沿着这些行的某些内容,而不是运行相同的查询两次。 – 2013-04-26 12:12:48
@DavidSöderlund:自“SQL Server 2005”以来,您可以做到这一点。 – Quassnoi 2013-04-26 12:13:54
可以请你提供,例如 – Xerxes 2013-04-26 12:15:15