gpt4 book ai didi

sql - 是否可以计算 group by 中一列的总和?

转载 作者:行者123 更新时间:2023-12-04 18:20:31 26 4
gpt4 key购买 nike

我有一个生成下表的 sql 查询,但我希望能够获得按类别分组的标记列的总数: enter image description here

代码如下:

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

最佳答案

您可以使用 sum() 窗口函数执行此操作。您实际上可以将其与常规聚合函数嵌套在一起。所以:

sum(count(it.ID)) over () as TotalCnt,
sum(sum(mc.ots)) over () as TotalImps

这假定您使用的是 SQL Server 2005 或更高版本。

这是为“整列”做的。对于子组,例如由类别定义的子组,同样的想法也成立(正如 Alexander 所指出的):

sum(count(it.ID)) over(按类别划分)作为 CategoryCnt,sum(sum(mc.ots)) over (partition by category) as CategoryImps

关于sql - 是否可以计算 group by 中一列的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16237740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com