Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
k_cire0426
Yak Posting Veteran
63 Posts |
Posted - 2009-02-04 : 17:29:17
|
hi I'm just new here. Welcome to me.. Anyway, is it possible to query a rows base on group and base on quotient of rows? QUOTIENT OF ROWS? let me explain this Example:col1|col2-----------1 test --1 test |1 test > 5 rows/2(divisor) = 2 + remainder 1 = 3 rows1 test |1 test --2 test --2 test > 4 rows/2(divisor) = 2 + remainder 0 = 2 rows 2 test |2 test --this should be the result:col1|col21 test --1 test > this is the [b]3 rows[\b]1 test --2 test \ 2 test / this is the [b]2 rows[\b]And also this must be in a VIEW.I am wondering if this is can be handled by ROW_NUMBER() function. |
|
|
sodeep
Master Smack Fu Yak Hacker
7174 Posts |
Posted - 2009-02-04 : 18:37:43
|
| [code]--Create TVDeclare @t table(col1 int, col2 char(8))--Prepare Sample DataInsert @tSelect 1,'test' union allSelect 1,'test' union allSelect 1 ,'test' union allSelect 1 ,'test' union allSelect 1 ,'test' union allSelect 2 ,'test' union allSelect 2 ,'test' union allSelect 2 ,'test' union allSelect 2 ,'test'--Roll SQL WheelSelect col1,col2from(Select col1,col2,Ntile(2)/*Since you have 2 groups */Over(Partition by col1 order by col1)as [Ntile]from @t)zWhere [Ntile] = 1--outputcol1 col21 test 1 test 1 test 2 test 2 test [/code] |
 |
|
|
k_cire0426
Yak Posting Veteran
63 Posts |
Posted - 2009-02-04 : 18:51:01
|
| Hi thanks to you,but what if you don't know exactly how may groups are there?and the divisor is not actually the number of groups it could be 3 or 4 etc..it is regardless of how many groups does the table had. |
 |
|
|
sodeep
Master Smack Fu Yak Hacker
7174 Posts |
Posted - 2009-02-04 : 20:05:03
|
| [code]--Create TVDeclare @t table(col1 int, col2 char(8))--Prepare Sample DataInsert @tSelect 1,'test' union allSelect 1,'test' union allSelect 1 ,'test' union allSelect 1 ,'test' union allSelect 1 ,'test' union allSelect 2 ,'test' union allSelect 2 ,'test' union allSelect 2 ,'test' union allSelect 2 ,'test'--Roll SQL WheelDeclare @Z intSet @Z =(Your Query to find number of groups)Select col1,col2from(Select col1,col2,Ntile(@Z) Over(Partition by col1 order by col1)as [Ntile]from @t)zWhere [Ntile] = 1--outputcol1 col21 test 1 test 1 test 2 test 2 test [/code] |
 |
|
|
|
|
|
|
|