I have a query that I always want to return 10 records for:
set rowcount 10
select row_number() over(order by count(*) desc) row_num
,hist_report_id
,max(rpt_report_name) report_name
from utility.dbo.tbl_report_history
join utility.dbo.tbl_report_definitions
on hist_report_id = rpt_report_id
where hist_user_id = 1038
group by hist_report_id
Which works fine if I have 10 or more records. The problem is when there are less than 10 records, I still need to return the rownumber field with nulls in the report_id and report_name fields.
If there were only 7 records returned, the results should look like:
row_num report_id report_name
1 id1 name1
2 id2 name2
3 id3 name3
4 id4 name4
5 id5 name5
6 id6 name6
7 id7 name7
8 null null
9 null null
10 null null
Any suggestions?
I am using SQL Server 2008
count()can never return less than zero… so just append 10 dummy rows with -1 in the count column via unionAlso, don’t use SET ROWCOUNT because it affects intermediate results