1
select top 1 ROW_NUMBER() OVER (ORDER BY eventtime desc) as id,
Eventcode, eventtime as et, status from cfw.dbo.DCTBLEVENTINFO 
where MeterID = 4722 and EventTime between convert(date,'2011-10-21') 
and dateadd(day,1,convert(date,'2011-10-26')) 
and EventCode = 13

原始结果集:

id  Eventcode   et                    status
1   13        2011-10-26 15:00:00.000   1

上面的查询返回了完美的结果集,但是如果我像下面这样使用相同的查询,它会返回错误的结果

SELECT temp.et 
  FROM (SELECT TOP 1 ROW_NUMBER() OVER (ORDER BY eventtime desc) as id,
               Eventcode, 
               eventtime as et, 
               status 
          FROM cfw.dbo.DCTBLEVENTINFO 
         WHERE MeterID = 4722 
           AND EventTime BETWEEN CONVERT(date,'2011-10-21') 
                             AND DATEADD(day,1,convert(date,'2011-10-26')) 
           AND EventCode = 13) temp 
 WHERE status = 1

上述查询的结果集:

et
------------------------
2011-10-21 21:42:00.000

它返回某个其他日期。我找不到问题。

4

2 回答 2

3

尝试将 ORDER BY 添加到您的子选择中。

就像是

select  temp.et 
from    (
            select  top 1 
                    ROW_NUMBER() OVER (ORDER BY eventtime desc) as id, 
                    Eventcode, 
                    eventtime as et, 
                    status 
            from    cfw.dbo.DCTBLEVENTINFO  
            where   MeterID = 4722 
            and     EventTime between convert(date,'2011-10-21') and dateadd(day,1,convert(date,'2011-10-26'))  
            and     EventCode = 13
            ORDER BY eventtime desc
        )   temp 
where   status=1

请始终记住,如果没有 ORDER BY,则没有默认排序顺序。

此外,请记住逻辑查询处理阶段 - 语句执行顺序

  1. 在哪里
  2. 通过...分组
  3. 立方体 | 卷起
  4. 拥有
  5. 选择
  6. 清楚的
  7. 订购方式
  8. 最佳
于 2012-08-22T04:01:33.170 回答
0
select top 1 temp.et from (select ROW_NUMBER() OVER (ORDER BY eventtime desc) as id,
Eventcode, eventtime as et, status from cfw.dbo.DCTBLEVENTINFO 
where MeterID = 4722 and EventTime between convert(date,'2011-10-21') 
and dateadd(day,1,convert(date,'2011-10-26')) 
and EventCode = 13 ORDER BY eventtime desc)temp where status=1

而不是只限制子查询中的一行,而是获取完整的结果,检查状态并单独限制第一行。

于 2012-08-22T04:01:55.293 回答