SQL SERVER: TOP 10 rows per field - if less than 10 rows then display empty rows -
i need select top 10 acct rows based on sys_cd value. hence wrote below query. query working fine.
select sys_cd, acct, cntacct ,rowid ( select sys_cd, acct, count(acct) cntacct, row_number() on (partition sys_cd order count(acct) desc ) rowid [fcidial].[dbo].table1 err_cd != 'y' group sys_cd, acct ) tmp rowid <= 10 order sys_cd, rowid, acct;
it providing below result
sys_cd fin_aaat cntfin_aaat rowid aaa 606000 4 1 aaa 566000 3 2 aaa 503200 1 3 bbb 251260 42433978 1 bbb 400601 41181797 2 bbb 400401 8399908 3 bbb 503200 2087703 4 bbb 604000 40795 5 bbb 130039 4748 6 bbb 252000 655 7 bbb 736000 40 8 bbb 735000 38 9 bbb 734000 36 10 ccc 233210 73611 1 ccc 464250 39397 2 ccc 186020 35231 3 ccc 265155 4949 4
the query result correct.
but expected output is, sys_cd if rowid less 10 display blank rows remaining rows.
example: in above 'aaa' present 3 rowids. need display 7 blank rows.
'bbb'is present 10 rowids. no need of blank rows. 'ccc' present 4 rowids, need display 6 blank rows.
i expect below output.
sys_cd acct cntacct rowid aaa 606000 4 1 aaa 566000 3 2 aaa 503200 1 3 - blank row - blank row - blank row - blank row - blank row - blank row - blank row - blank row bbb 251260 42433978 1 bbb 400601 41181797 2 bbb 400401 8399908 3 bbb 503200 2087703 4 bbb 604000 40795 5 bbb 130039 4748 6 bbb 252000 655 7 bbb 736000 40 8 bbb 735000 38 9 bbb 734000 36 10 ccc 233210 73611 1 ccc 464250 39397 2 ccc 186020 35231 3 ccc 265155 4949 4 - blank row - blank row - blank row - blank row - blank row - blank row - blank row - blank row
how can achieve desired result.
you need values sys_cd
, , table of numbers 1 - 10:
select ccd.sys_cd, n.rowid (select distinct sys_cd [fcidial].[dbo].table1 err_cd != 'y') ccd cross join (values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) n (rowid);
once have can left join
original query, end null
missing records:
with tmp ( select sys_cd, acct, count(acct) cntacct, row_number() on (partition sys_cd order count(acct) desc) rowid [fcidial].[dbo].table1 err_cd != 'y' group sys_cd, acct ) select ccd.sys_cd, tmp.acct, tmp.cntacct, n.rowid (select distinct sys_cd [fcidial].[dbo].table1 err_cd != 'y') ccd cross join (values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) n (rowid) left join tmp on tmp.sys_cd = ccd.sys_cd , tmp.rowid = n.rowid order ccd.sys_cd, n.rowid;
Comments
Post a Comment