回答

收藏

SQL Select Records based on current date minus two days

技术问答 技术问答 202 人阅读 | 0 人回复 | 2023-09-14

I have an orders table which contains an order ID, order date and order
; o1 o1 P- m3 Cdescription.9 }% a: R/ c' X
I want to run a select query which captures all orders that have been created
9 y! |2 F/ o" t( ?; Oin the last two days. so the current date minus two days. from the 14th
& u0 a7 G0 m3 t7 P" A$ mDecember, I would want to select all orders where the order date is > 13th
2 B1 x2 a3 ~; u. k( SDecember. This needs to use a Get date function to pick up the current date
; n; M; S( J  A) Zand minus the days.
2 e3 ?- z0 \4 Y* b  F8 gI have tried:/ _* w% y* z9 t7 q* ^: @7 V
select * from orders where orderdate > getdate() - 2
1 i# z# i7 X& g0 U6 C) _/ F0 z: }+ Y6 |- rbut this is not producing the correct results. Any idea’s how to do this
$ p5 r) ~1 B" c9 Y% N1 A- lplease?
6 s+ |" s; D3 N/ w/ n/ E                + c. g2 B( g3 u6 b' _! x
解决方案:
, O/ @6 g# S' r, l% s! |5 q, G, I                0 U( z, S1 g6 c
" F+ S$ p3 J! m+ c: Q9 D0 M, u& {6 ~/ e

. w/ Q, |' \' m1 {                you should try to use dateadd function
( B: }) o- D1 _* W2 K  h( Iselect * from orders where orderdate > dateadd(dd,-1,cast(getdate() as date))
% A/ ~- B& |9 z" d! c1 Y% iNow this may exactly what you need but then you need to understand that by. T# P* ~9 h7 ~9 r* _3 z. [7 u# X
casting to date we remove the time part and effectively going back to start of, d" I) M# F( i0 u
the day and a day behind it(-1) gives the start of yesterday.
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则