I have a stored procedure that returns a set of rows for each ActivityUnitId.
What is needed is the Top 10 rows for each ActivityUnitId based on Hours. I have managed to achieve this, my query looks like
With Data AS
(SELECT
ProjectID,ActivityUnitID,Description,GroupID,
SUM(Hours) AS NoiseHours,
ROW_NUMBER() OVER(PARTITION BY ActivityUnitID ORDER BY SUM(Hours) DESC) as 'RowNum'
FROM
tbl_Sub
INNER JOIN
tbl_AnalysisData ON tbl_Sub.SubActivityID = tbl_AnalysisData.SubActivityID
INNER JOIN
tbl_Analysis ON tbl_AnalysisData.LookupID = tbl_Analysis.LookupID
INNER JOIN
tbl_ActivityUnit ON tbl_ActivityUnit.ActivityUnitID = tbl_Sub.ActivityUnitID
tbl_Suby.ProjectID = @ProjectID
AND
tbl_Sub.ActivityUnitID = ISNULL(@ActivityUnitID,tbl_Sub.ActivityUnitID)
GROUP BY
ActivityUnitID,ProjectID, Description,AUGroupID
) SELECT * from Data where RowNum<=10
The ‘RowNum’ column contains Row number for each row, value of which has been assigned based to hours. So the First 10 rows contain the rows with top 10 hours.
Now what I want is to add an Extra summary Row in the end for each ActivityUnitID. This will contain the sum of Hours for all the rows that have been left out i.e. summary Row for
RowNum > 10
So what I’ll have in the end is Top 10 rows for each ActivityUnitID + an extra row that would sum up the hours for other rows for that ActivityUnitID
For example lets say I have a table with 2 cols
ID Hours RowNum
1A 30 1
2B 20 2
3C 10 3
4D 5 4
5E 4 5
6F 3 6
How do I do a select on this so that I get Rows where RowNum <=3 and another row With summation of others
ID Hours
1A 30
2B 20
3C 10
Oth 12
The simplest way would be to
UNIONthose totals with the data you already haveYour complete statement could then look something like this
The difficulty when using a union is that both parts of the union should have the same amount and same type of columns, hence the need for adding dummy columns to the select.