patternsqlMinor
Need to divide single column into multiple columns
Viewed 0 times
dividecolumnscolumnneedintosinglemultiple
Problem
My table has data with a single column:
And I want output like this:
Another has two columns like this:
And I want it to display like this:
1
2
3
4
5
6
7
8
9
10And I want output like this:
1 2 3 4 5-first row
6 7 8 9 10 - second rowAnother has two columns like this:
Column 1 Column 2
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h
9 i
10 jAnd I want it to display like this:
1 a 2 b 3 c 4 d 5 e-first row
6 f 7 g 8 h 9 i 10 j - second rowSolution
For the first case you can use
SQL Fiddle
For the second case Oracle has a straight forward syntax to achieve this with
SQL Fiddle
ROW_NUMBER then PIVOT to do this using the modulo operator to divide into columns and the result of integer divsion by 5 to group into rows.WITH CTE AS
(
SELECT C,
(ROW_NUMBER() OVER (ORDER BY C) -1)%5 AS Col,
(ROW_NUMBER() OVER (ORDER BY C) -1)/5 AS Row
FROM YourTable
)
SELECT [0], [1], [2], [3], [4]
FROM CTE
PIVOT (MAX(C) FOR Col IN ([0], [1], [2], [3], [4])) AS Pvt
ORDER BY RowSQL Fiddle
For the second case Oracle has a straight forward syntax to achieve this with
PIVOT. SQL Server doesn't but you can do this as below.WITH CTE AS
(
SELECT *,
(ROW_NUMBER() OVER (ORDER BY Column1) -1)%5 AS Col,
(ROW_NUMBER() OVER (ORDER BY Column1) -1)/5 AS Row
FROM YourTable
)
SELECT MAX(CASE WHEN Col = 0 THEN Column1 END),
MAX(CASE WHEN Col = 0 THEN Column2 END),
MAX(CASE WHEN Col = 1 THEN Column1 END),
MAX(CASE WHEN Col = 1 THEN Column2 END),
MAX(CASE WHEN Col = 2 THEN Column1 END),
MAX(CASE WHEN Col = 2 THEN Column2 END),
MAX(CASE WHEN Col = 3 THEN Column1 END),
MAX(CASE WHEN Col = 3 THEN Column2 END),
MAX(CASE WHEN Col = 4 THEN Column1 END),
MAX(CASE WHEN Col = 4 THEN Column2 END)
FROM CTE
GROUP BY Row
ORDER BY RowSQL Fiddle
Code Snippets
WITH CTE AS
(
SELECT C,
(ROW_NUMBER() OVER (ORDER BY C) -1)%5 AS Col,
(ROW_NUMBER() OVER (ORDER BY C) -1)/5 AS Row
FROM YourTable
)
SELECT [0], [1], [2], [3], [4]
FROM CTE
PIVOT (MAX(C) FOR Col IN ([0], [1], [2], [3], [4])) AS Pvt
ORDER BY RowWITH CTE AS
(
SELECT *,
(ROW_NUMBER() OVER (ORDER BY Column1) -1)%5 AS Col,
(ROW_NUMBER() OVER (ORDER BY Column1) -1)/5 AS Row
FROM YourTable
)
SELECT MAX(CASE WHEN Col = 0 THEN Column1 END),
MAX(CASE WHEN Col = 0 THEN Column2 END),
MAX(CASE WHEN Col = 1 THEN Column1 END),
MAX(CASE WHEN Col = 1 THEN Column2 END),
MAX(CASE WHEN Col = 2 THEN Column1 END),
MAX(CASE WHEN Col = 2 THEN Column2 END),
MAX(CASE WHEN Col = 3 THEN Column1 END),
MAX(CASE WHEN Col = 3 THEN Column2 END),
MAX(CASE WHEN Col = 4 THEN Column1 END),
MAX(CASE WHEN Col = 4 THEN Column2 END)
FROM CTE
GROUP BY Row
ORDER BY RowContext
StackExchange Database Administrators Q#44598, answer score: 7
Revisions (0)
No revisions yet.