我有一个sql查询,它生成下表,但我希望能够获得按类别分组的标记列的总数:
这是代码:
select pic.Name as Category,
pis.Code as Code,
pis.Name as Issue,
count(it.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(it.ID) * 100) as 'unfav %',
(sum(case when ito.Rating =50 then 1.0 else 0.0 end) / count(it.ID) * 100) as 'neu %',
(sum(case when ito.Rating >50 then 1.0 else 0.0 end) / count(it.ID) * 100) as 'fav %',
CONVERT(decimal(4,2),avg(ito.Rating)) as 'Av Rating %',
count(it.id) * 100.0 / sum(count(it.ID)) OVER () AS [% of Count],
sum(mc.ots) * 100.0 / sum(sum(mc.ots)) OVER () AS [% Imps]
from
Profiles P
INNER JOIN ProfileResults PR ON P.ID = PR.ProfileID
INNER JOIN Items it ON PR.ItemID = It.ID
inner join Batches b on b.ID=it.BatchID
left outer join BatchActionHistory bah on b.ID=bah.batchid
inner join itemorganisations oit (nolock) on it.id=oit.itemid
inner join itemorganisations ito (nolock) on it.id=ito.itemid
inner join itemorganisationIssues ioi (nolock) on ito.id=ioi.itemorganisationid
inner join ProjectIssues pis (nolock)on ioi.IssueID = pis.ID
inner join ProjectIssueCategories pic (nolock)on pic.ID = pis.CategoryID
inner join Lookup_ItemStatus lis (nolock) on lis.ID = it.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 = it.MediaChannelID
where p.ID = @profileID
and b.StatusID IN (6,7)
and bah.BatchActionID = 6
and it.StatusID = 2
and it.IsRelevant = 1
Group BY pic.Name,pis.Name,pis.Code
order by pic.name
答案 0 :(得分:4)
您可以使用sum()
窗口功能执行此操作。实际上,您可以使用常规聚合函数来嵌套它。所以:
sum(count(it.ID)) over () as TotalCnt,
sum(sum(mc.ots)) over () as TotalImps
这假设您使用的是SQL Server 2005或更高版本。
这适用于“整栏”。对于一个子组,例如由一个类别定义的子组,同样的想法成立(如亚历山大所指出的):
sum(count(it.ID))over(按类别划分)为CategoryCnt, sum(sum(mc.ots))over(按类别划分)为CategoryImps
答案 1 :(得分:2)
阅读WITH ROLLUP
子句(或分组集,在sql server的更高版本中可用 - 我不知道你在使用哪一个)。
它将按GROUP BY
的列组合对您的输出进行分组(3列分组,2列分组,1列分组和总计)。然后,您可以在聚合时使用GROUPING(column_name)= 1来区分分组列。
希望这会有所帮助。