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. 選択する
  9. 明確
  10. オーダーバイ
于 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

サブクエリで 1 行のみを制限する代わりに、完全な結果を取得し、ステータスを確認して、最初の行のみを制限します。

于 2012-08-22T04:01:55.293 に答える