|
我有一张桌子,上面有我所有顾客购买的东西。我想选择上周(从周日开始的一周)中的所有条目。) h! W, d* |9 s* B
id value date
, S: N4 O; ^" M+ Q! H2 R5907 1.20 "2015-06-05 09:08:34-03") ]8 ]% w4 v3 T2 P6 \8 o9 ^1 V
5908 120.00 "2015-06-09 07:58:12-03"
& L1 |1 k- {3 ]# a& E+ Y我已经试过了:+ S5 ^9 G1 R. N& k
SELECT id, valor, created, FROM compras WHERE created >= now() - interval '1 week' and parceiro_id= '1'
+ X! b" n9 D0 |, e! l但是我得到了上周的数据,包括本周的数据,我只想要上周的数据。
6 s" b# i8 ?3 H7 {如何只获取上周的数据?
: T; P9 V' q- S" G! k5 W/ b 4 |$ [/ o) ^1 x" {3 j& p# F
解决方案:
i! c3 l; `6 u1 A
5 S6 O5 H: O. @2 E
, r* u; Z' j: G1 n$ U; j% H% c4 u! A- X0 d7 p8 o$ ?
此条件将返回上周日至周六的记录:
) F2 M! u6 o9 k6 J: Y! D. m7 H. aWHERE created BETWEEN* |3 O& ^$ I# h" W3 u
NOW():ATE-EXTRACT(DOW FROM NOW())::INTEGER-7 7 L, G+ S# `, r% z
AND NOW():ATE-EXTRACT(DOW from NOW())::INTEGER" n4 A9 a$ i+ B9 j+ o j& V1 \" ?
有一个例子:
4 `/ A4 T* v, C- qWITH compras AS (
* j4 _ F1 ^, M X ? SELECT ( NOW() + (s::TEXT || ' day')::INTERVAL )::TIMESTAMP(0) AS created
6 J. I" X) M) r- d! v. Q FROM generate_series(-20, 20, 1) AS s/ o1 W0 s. M2 P+ x
): f7 T6 u2 ~6 y0 o& c5 P& p1 Y5 X
SELECT to_char( created, 'DY'::TEXT), created
4 S; Y! q# R HFROM compras
& v+ @5 M+ i& lWHERE created BETWEEN; ^! _5 A" @5 X* x _
NOW():ATE-EXTRACT(DOW FROM NOW())::INTEGER-7
8 a' V3 y% i9 x AND NOW():ATE-EXTRACT(DOW from NOW())::INTEGER) ^6 e" |' Y( u1 y2 g, a: _
在对@ d456的回答中:" m6 ]! \% t" e) ?. O- u3 q6 F. e& x
+ j0 e# M8 w) L7 B. s- m
BETWEEN在间隔的两端不使用星期日的午夜吗?
% t! w8 x& T# j7 Y) V7 L
3 V( I6 p; M- `1 e$ @2 e; ]没错,BETWEEN包括间隔两端的周日午夜。要在间隔结束时排除周日的午夜,必须使用运算符>=和, I9 V h" t4 I$ I# @* q3 S/ ?2 e
WITH compras AS (
0 @! d: c0 L. _. u2 T8 ]# ~2 v SELECT s as created! r3 d* n: A$ X4 P! q A+ t
FROM generate_series( -- this would produce timestamps with 20 minutes step& i# q5 K" M% c) e( |5 Z
(now() - '20 days'::interval)::date,
/ a( {, c+ {# s& \2 C3 r/ n (now() + '20 days'::interval)::date,
. @- g" X7 r C' v '20 minutes'::interval) AS s; ^) b/ [8 j* c$ X/ o: ]# {- [
)3 d7 M; i- e) x }
SELECT to_char( created, 'DY'::TEXT), created
7 W) S$ O9 t$ X: s CFROM compras
1 A1 A& L9 Q8 _4 { ?9 eWHERE TRUE
5 R& z: g% M+ x, f' L AND created >= NOW():ATE-EXTRACT(DOW FROM NOW())::INTEGER-7
& {: {- A6 o4 b# J c. q. j AND created < NOW():ATE-EXTRACT(DOW from NOW())::INTEGER |
|