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
它会返回其他日期。我找不到问题。
答案 0 :(得分: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
请永远记住Without ORDER BY, there is no default sort order.
此外,请记住Logical Query Processing Phases – Order of Statement Execution
- FROM
- ON
- OUTER
- WHERE
- GROUP BY
- CUBE | ROLLUP
- HAVING
- 选择
- DISTINCT
- ORDER BY
- TOP
醇>
答案 1 :(得分: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
不是仅限制子查询中的一行,而是获取完整的结果,检查状态并仅限制第一行。