NTILE with a variable sample


  


-- Create Sample Table

Declare @GroupRelation_Test TABLE (
	MD_Group [varchar](20),
	CustomerNumber [varchar](20) , 
	AmountBilled [varchar](20) ,
    MinAmounttBilled [varchar](20) 
)



-- Test data

INSERT INTO @GroupRelation_Test

      ( CustomerNumber, AmountBilled,MinAmounttBilled)

SELECT		'12',	'15243'	,'' UNION ALL
SELECT		'1231234',	'15243'	,'' UNION ALL
SELECT		'463',	'15243'	,'' UNION ALL
SELECT		'442',	'15243'	,'' UNION ALL
SELECT		'4324',	'15243'	,'' UNION ALL
SELECT		'3123',	'15243'	,'' UNION ALL
SELECT		'67123',	'15243'	,'' UNION ALL
SELECT		'109988',	'15243'	,'' UNION ALL
SELECT		'74665',	'15243'	,'' UNION ALL
SELECT		'23323',	'15243'	,'' UNION ALL
SELECT		'9866',	'15243'	,''  
 


Declare @intForNtile int
  Set @intForNtile = Ceiling((Select count(*) from @GroupRelation_Test)/ 3.0) 
  --Make 3 as decimal 

select ntile(@intForNtile) Over(Order by newid()) MD_Group
, * from @GroupRelation_Test
 

https://social.msdn.microsoft.com/Forums/en-US/74ed0a9f-2ca4-4d97-9ce6-d95cf1528819/grouping-data-within-a-db-table?forum=transactsql

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s