Monday, October 24, 2011

Splitting SQL results into 2 or more groups/tables

Came across a need recently to split a result set into two output tables to achieve a certain layout requirement. SQL 2008 (2005 actually, but why?) makes life so much easier than creating a temp table or taxing joins. The code sample uses NTILE(n) and Over() ranking function to pull roughly equal result sets. Change the value passed to  NTILE() for any number of result sets. I used this output to populate two strongly typed data sets.

------------------------------------
-- Table 0 - Items for group 1
-------------------------------------
SELECT [ItemID] = AutoID, Column2, Column3, Column4 FROM (
SELECT NTILE(2) OVER(ORDER BY AutoID) as GroupID, * FROM dbo.[SourceDataTable] [WHERE CLAUSE]
) [ArbitraryTableName]
WHERE [ArbitraryTableName].GroupID = 1
 
------------------------------------
-- Table 1 - Items for group 2
-------------------------------------
SELECT [ItemID] = AutoID, Column2, Column3, Column4 FROM (
SELECT NTILE(2) OVER(ORDER BY AutoID) as GroupID, * FROM dbo.[SourceDataTable] [WHERE CLAUSE]
) [ArbitraryTableName]
WHERE [ArbitraryTableName].GroupID = 2

No comments:

Post a Comment