Reputation: 173
I have a table [Tbl1] containing two fields.
ID as int And TextValue as nvarchar(max)
Suppose there are 7 records. I need a resultset that has two columns Text1 and Text2. The Text1 should have first 4 records and Text2 should have remaining 3 records.
Now, the result-set should have
Upvotes: 1
Views: 1220
Reputation: 344301
I wonder how this can be useful, but I think you could try the following:
SELECT t1.TextValue AS Text1,
t2.TextValue AS Text2
FROM tbl1 t1
LEFT JOIN tbl1 t2 ON ((t2.id - 4) = t1.id)
WHERE t1.id <= 4;
Test case:
CREATE TABLE tbl1 (id int, textvalue varchar(15));
INSERT INTO tbl1 VALUES(1, 'Apple');
INSERT INTO tbl1 VALUES(2, 'Mango');
INSERT INTO tbl1 VALUES(3, 'Orange');
INSERT INTO tbl1 VALUES(4, 'Pineapple');
INSERT INTO tbl1 VALUES(5, 'Banana');
INSERT INTO tbl1 VALUES(6, 'Grapes');
INSERT INTO tbl1 VALUES(7, 'Sapota');
Result:
+-----------+--------+
| Text1 | Text2 |
+-----------+--------+
| Apple | Banana |
| Mango | Grapes |
| Orange | Sapota |
| Pineapple | NULL |
+-----------+--------+
UPDATE:
As @AlexCuse suggested in a comment below, you could also use a variable to get the row count of the table, in order to have a query that works for any number of rows:
DECLARE @x float;
SET @x = ROUND((SELECT COUNT(*) FROM tbl1) / 2.0, 0);
SELECT t1.TextValue AS Text1,
t2.TextValue AS Text2
FROM tbl1 t1
LEFT JOIN tbl1 t2 ON ((t2.id - @x) = t1.id)
WHERE t1.id <= @x;
Upvotes: 2
Reputation: 332571
Use:
SELECT t.textvalue AS text1,
(SELECT x.textvalue
FROM TBL x
WHERE x.id = t.id + 4) AS text2
FROM TBL t
WHERE t.id <= 4
Upvotes: 1