SQL query for getting data in two fields from one column
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 | Grap开发者_JAVA技巧es
Orange | Sapota
Pineapple |
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;
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
精彩评论