我有以下数据并使用SQL Server 2005
UserID UserName LogTime LogDate
1 S 9:00 21/5/2010
1 S 10:00 21/5/2010
1 S 11:00 21/5/2010
1 S 12:00 21/5/2010
1 S 14:00 21/5/2010
1 S 17:00 21/5/2010
需要输出为: -
1 S 21/5/2010 9:00 21/5/2010 10:00
1 S 21/5/2010 11:00 21/5/2010 12:00
1 S 21/5/2010 14:00 21/5/2010 17:00
我在查询中使用了ROW_NUMBER函数,但显示错误
答案 0 :(得分:1)
我想知道问题是否比你说的还要多。严格按照您提供的信息,以下示例似乎有效。
DECLARE @YourTable TABLE(UserId int, UserName varchar(10), LogTime time, LogDate date)
insert @YourTable values(1,'S','9:00','5/21/2010')
insert @YourTable values(1,'S','10:00','5/21/2010')
insert @YourTable values(1,'S','11:00','5/21/2010')
insert @YourTable values(1,'S','12:00','5/21/2010')
insert @YourTable values(1,'S','14:00','5/21/2010')
insert @YourTable values(1,'S','17:00','5/21/2010');
WITH
[TableWithRowId] as
(SELECT ROW_NUMBER() OVER(ORDER BY UserId,LogDate,LogTime) RowId, * FROM @YourTable),
[OddRows] as
(SELECT * FROM [TableWithRowId] WHERE rowid % 2 = 1),
[EvenRows] as
(SELECT *, RowId-1 As OddRowId FROM [TableWithRowId] WHERE rowid % 2 = 0)
SELECT
[OddRows].UserId,
[OddRows].UserName,
[OddRows].LogDate,
[OddRows].LogTime,
[EvenRows].LogDate,
[EvenRows].LogTime
FROM
[OddRows] LEFT JOIN [EvenRows]
ON [OddRows].RowId = [EvenRows].OddRowId