2013-04-26 40 views
3

我有產生如下表的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 

回答

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))(按分類劃分)作爲CategoryImps

+0

這個總和只是該組的總數或整個結果集? – Xerxes 2013-04-26 13:37:02

+1

@xerxes在回答建議由Gordon Linnhoff嘗試添加OVER(PARTITION BY pis.Code) – 2013-04-26 14:01:06

+0

謝謝,它工作:) – Xerxes 2013-04-26 14:07:31

2

閱讀關於WITH ROLLUP子句(或分組集,在SQL Server的更高版本中可用 - 我不知道你使用哪一個)。 它將按照組合GROUP BY(3列組,2列組,1列組和總計)的組合將輸出分組。然後,您可以在聚合時使用GROUPING(column_name)= 1區分分組列。 希望這有助於。

相關問題