0

如何查看单行的前 2 行

表格1

id  name     value size   result
----------------------------------
001 rajan    100   280DD   100%
002 Vijayan  200   120DD    80%
003 Sidarth  300   150DD    90%
004 Rakesh   400   270DD    95%
...

我想在单行中选择前 2 行....

预期产出

id id name name value value size size result result
---------------------------------------------------------    
001 002 rajan vijayan 100 200 280DD 120DD 100% 80%
003 004 Sidarth Rakesh 300 400 150DD 270DD 90% 95%
.....

这该怎么做?

4

2 回答 2

2
SELECT 
    t.Id, tt.Id, t.name, tt.name, t.value, tt.value, t.size, tt.size, t.result, tt.result
FROM YourTable t
INNER JOIN YourTable tt ON tt.Id = t.Id + 1
WHERE tt.Id % 2 = 0

这对我行得通。希望对您有所帮助。

如果您仍然需要帮助,请尝试一下。

Declare @TempTable as table (FirstId int, SecondId int null, FirstCaption nvarchar(max), SecondCaption nvarchar(max) null, FirstDescription nvarchar(max), SecondDescription nvarchar(max) null)

DECLARE @TempId int DECLARE curs CURSOR FOR SELECT ID FROM Categories open curs fetch next from curs into @TempId WHILE @@FETCH_STATUS = 0 begin IF (@TempId % 2 = 1) BEGIN INSERT INTO @TempTable SELECT t.Id, null, t .Caption, null, t.Description, null FROM categories t WHERE t.Id = @TempId

    END
ELSE
    BEGIN
        UPDATE @TempTable SET SecondId = t.Id, SecondCaption = t.Caption, SecondDescription = t.Description
        FROM categories t
        INNER JOIN @TempTable tt ON tt.FirstId = @TempId - 1
        WHERE t.Id = @TempId
    END
fetch next from curs into @TempId

结束关闭 curs 解除分配 curs

选择 * 从 @TempTable

于 2012-05-26T08:01:03.153 回答
0
with cte as (
select row_number() over (order by id) as rn,
* from Table1
)
select a.id, b.id, a.name, a.value, b.value, a.size, b.size, a.result, b.result
from cte a join cte.b on a.id = b.id - 1

where a.rn <insert your criteria for which to show, for example in (1,3,5,7) or a modulus operator to see every 2nd row to avoid duplicate data>
于 2012-05-26T08:05:13.443 回答