SQL查询时间间隔。语法错误。

时间:2013-02-26 22:04:41

标签: sql sql-server sql-server-2008 group-by

在这种情况下,看似简单的练习变成了什么。我甚至无法直接获得语法。

Readings表包含多个用户的坐标和时间读数。我现在想要的只是为每个用户组织连续的时间间隔。

数据

CREATE TABLE [Readings] (
user_id varchar(10),
reading_time int, 
x decimal(10,2),
y decimal(10,2) );


INSERT INTO Readings VALUES  
('u1', 60, 345, 400),
('u1', 100, 560,300), 
('u2', 35, 1024, 250), 
('u1', 90, 450, 450), 
('u3', 150, 600, 100), 
('u3', 100, 500, 125);

我的错误代码

SELECT r.user_id, r.reading_time start_time, rm.reading_time end_time, 
       (CONVERT(varchar, r.x)+' ; '+CONVERT(varchar, r.y)) start_point, 
       (CONVERT(varchar, rm.x)+' ; '+CONVERT(varchar, rm.y)) end_point 
FROM Readings r 
JOIN (SELECT TOP 1 r2.user_id, r2.reading_time, r2.x, r2.y
      FROM Readings r2
      WHERE r2.user_id=r.user_id and 
            r2.reading_time < r.reading_time
      ORDER BY r2.reading time desc) rm 
ON r.user_id=rm.user_id
ORDER BY 1,2 desc;

请指出我的语法错误?

2 个答案:

答案 0 :(得分:3)

您不能像这样使用JOIN,您需要使用CROSS APPLYOUTER APPLY(假设是SQL Server)。另外,请为varchars添加长度。现在,试试这个:

SELECT r.user_id, r.reading_time start_time, rm.reading_time end_time, 
       (CONVERT(varchar(10), r.x)+' ; '+CONVERT(varchar(10), r.y)) start_point, 
       (CONVERT(varchar(10), rm.x)+' ; '+CONVERT(varchar(10), rm.y)) end_point 
FROM Readings r 
OUTER APPLY (SELECT TOP 1 r2.user_id, r2.reading_time, r2.x, r2.y
             FROM Readings r2
             WHERE r2.user_id=r.user_id and 
                   r2.reading_time < r.reading_time
             ORDER BY r2.reading_time desc) rm 
ORDER BY 1,2 desc;

Here is a demo让你尝试。

答案 1 :(得分:2)

您的问题的一部分是您在子查询中引用表别名,只有在使用APPLY时才能这样做:

SELECT r.user_id, 
  r.reading_time start_time, 
  rm.reading_time end_time, 
  (CONVERT(varchar(10), r.x)+' ; '+CONVERT(varchar(10), r.y)) start_point, 
  (CONVERT(varchar(10), rm.x)+' ; '+CONVERT(varchar(10), rm.y)) end_point 
FROM Readings r 
CROSS APPLY
(
  SELECT TOP 1 r2.user_id, r2.reading_time, r2.x, r2.y
  FROM Readings r2
  WHERE r2.user_id=r.user_id and 
      r2.reading_time < r.reading_time
  ORDER BY r2.reading_time desc
) rm 
ORDER BY 1,2 desc;

请参阅SQL Fiddle with Demo