Sql-server – Return 2 rows at a time from SQL Server

querysql server

How can I slice up my table and return and evenly distribute the data?

Because I wanted to slice this up and put it into my 3 combo boxes in a windows form.

Example :

Table1

  ID          Name
   1           a
   2           b
   3           c
   4           d
   5           e

Windows Form Output :

combobox1   combobox2  combobox3
  a             c          e
  b             d

Best Answer

This code should achieve what you want

SELECT [1] AS [Combobox1], [2] AS [Combobox2], [3] AS [Combobox3]
FROM
(
    SELECT [name],
        NTILE(3) OVER (ORDER BY ID) AS [CB]
    FROM #Temp
    WHERE [ID]%2 <> 0
) src
PIVOT
(
    MAX([Name]) FOR [CB] IN ([1], [2], [3])
) pvt
UNION
SELECT [1] AS [Combobox1], [2] AS [Combobox2], [3] AS [Combobox3]
FROM
(
    SELECT [name],
        NTILE(3) OVER (ORDER BY ID) AS [CB]
    FROM #Temp
    WHERE [ID]%2 = 0
) src
PIVOT
(
    MAX([Name]) FOR [CB] IN ([1], [2], [3])
) pvt

Sample output:

Combobox1 Combobox2 Combobox3
--------- --------- ---------
a         c         e
b         d         NULL