tags:

views:

57

answers:

2

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.

[Tbl1]

ID | TextValue

1. | Apple

2. | Mango

3. | Orange

4. | Pineapple

5. | Banana

6. | Grapes

7. | Sapota

Now, the result-set should have


Text1 | Text2

Apple | Banana

Mango | Grapes

Orange | Sapota

Pineapple |

+2  A: 

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;
Daniel Vassallo
I also fail to see the usefulness, but you may want to get the total count first, and make it where t1.id <= Ceiling( (@cnt * 1.00) / 2), that way it is more flexible ;)
AlexCuse
@Alex: Yes I suppose that is what should be done.
Daniel Vassallo
+1: LEFT JOIN would be my preference
OMG Ponies
Its right answer but, Can I get same result without being dependent on ID.
AmiT
@AmitT: Yes, let me update the answer.
Daniel Vassallo
Still the answer is dependent on ID. If I replace the ID column with date field and there is no any order in dates. Now the text data after a specific date should come in 1st column and remaining in 2nd column. I am not sure, is it possible to get same result-set without using IDs
AmiT
@AmitT: Yes, I think what you require can be done with Pivots, as was suggested in the comments to your question. I recommend posting another question on this, maybe giving a couple of realistic examples which you like to group in this manner.
Daniel Vassallo
+1  A: 

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
OMG Ponies