我有一个包含两个字段的表[Tbl1]。
ID为int和 TextValue为nvarchar(max)
假设有7条记录。我需要一个有两列Text1和Text2的结果集。 Text1应该有前4条记录,Text2应该有剩余的3条记录。
现在,结果集应该有
答案 0 :(得分:2)
我想知道这有什么用处,但我想你可以尝试以下方法:
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;
测试用例:
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');
结果:
+-----------+--------+
| Text1 | Text2 |
+-----------+--------+
| Apple | Banana |
| Mango | Grapes |
| Orange | Sapota |
| Pineapple | NULL |
+-----------+--------+
<强>更新强>
在下面的评论中建议@ AlexCuse,您还可以使用变量来获取表的行数,以便有一个适用于任意行数的查询:
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;
答案 1 :(得分:1)
使用:
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