2012-01-30 152 views
0

指定數量的我有一個查詢,我一直想爲返回10個記錄:總是返回記錄SQL服務器

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 

,如果我有10分或更多的記錄,工作正常。問題是當記錄少於10條時,我仍然需要在report_id和report_name字段中返回帶有空值的rownumber字段。

如果只有7條記錄返回,結果應該是這樣的:

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 

有什麼建議?

我使用SQL Server 2008的

+0

SQL Server版本?我想你需要某種與臨時表或表變量的聯合。 – Blorgbeard 2012-01-30 14:40:15

回答

3

絕不能count()回報小於零......所以很合理牛逼通過工會在數列與附加-110個空行

另外,不要使用SET ROWCOUNT,因爲它影響中間結果

SELECT TOP 10 
    row_number() over(order by TheCount desc) AS row_num, 
    hist_report_id, 
    report_name 
FROM 
    (
    select 
     ,count(*) AS TheCount 
     ,hist_report_id 
     ,max(rpt_report_name) AS 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 
    UNION ALL 
    SELECT TOP 10 
     -1, NULL, NULL 
    FROM sys.columns 
    ) T 
+0

太棒了!我希望有一個單一的聲明解決方案,這完美的作品。 – ChandlerPelhams 2012-01-30 14:56:46

0

,我記得最簡單的方法:

  1. Insertselect result#temptable
  2. While count(*) < 10insertinto #temptable
0

你可以考慮使用一個TVF返回給你一組的,你可以用外連接數:

CREATE FUNCTION SetOfValues (@beginningAt int, @endingAt int, @step int = 1) 
RETURNS 
    @result TABLE (value int) 
AS BEGIN 
    declare @counter int set @counter = @beginningAt 
    while(@counter<[email protected]) 
    begin 
     insert into @result values(@counter) 
     set @counter = @counter + @step 
    end 
RETURN 
END 
GO 

-- USAGE 
with cte as (
    select row_number() over (order by hist_report_Id) as row_num, 
    hist_report_Id, report_name 
    from tbl_report_history join tbl_report_definitions on hist_report_Id = rpt_reportId) 
select value, hist_reportId, report_name 
from dbo.SetOfValues(1,10,1) as t on t.value = cte.row_num 
1
with 
/* Create 10 dummy rows using recursion */ 
RowSequence as (
    select 0 Idx 
    union all 
    select RowSequence.Idx+1 Idx from RowSequence where RowSequence.Idx+1<10 
    ), 
/* Your Query */ 
YourQuery as(
    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 
    ) 
/* Now all together */ 
select top 10 * from (
    select * from YourQuery 
    union all 
    select null, null, null from RowSequence 
    ) a 
/* To avoid the recursion maximum level 100 */ 
option (maxrecursion 0)