开发者

Query start and stop dates between two date fields

开发者 https://www.devze.com 2023-02-05 16:07 出处:网络
I have a start order date field and a stop order field I need to check the database to see if the start and stop orders are outside of any of the pay period start and end fields. Say 01-aug-10 and 14-

I have a start order date field and a stop order field I need to check the database to see if the start and stop orders are outside of any of the pay period start and end fields. Say 01-aug-10 and 14-aug-10 and 15-aug-10 and 28-aug-10 and 29-aug-10 and 11-sep-10 are all of the pay periods in one month. The start order 01-aug-10 and the end order is 14-aug-10. Yet when I do a SQL 开发者_如何学运维that said (where end order not between pay period start and pay period end) the 01-aug-10 to 14-aug-10 still shows up. My needs are if it finds any dates that match stop looking and go to the next record start order and stop order and start the next search till we hit the end of the record search requirements.

I am looking to search by month and by year to keep the query responsive. The database is quite large. My query seams like it only does the between check once and then it shows all of the data that does fit between the pay period start and stop, and that is the data I do not want to see!


What dbms?

So you have a table like this?

CREATE TABLE something
(
  pay_period_start date NOT NULL,
  pay_period_end date NOT NULL,
  CONSTRAINT something_pkey PRIMARY KEY (pay_period_start),
  CONSTRAINT something_pay_period_end_key UNIQUE (pay_period_end),
  CONSTRAINT something_check CHECK (pay_period_end > pay_period_start)
);
insert into something values ('2010-08-01', '2010-08-14');
insert into something values ('2010-08-15', '2010-08-28');
insert into something values ('2010-08-29', '2010-09-11');

Then I can run this query. ('2010-08-14' is the value of your stop order column or end order column or something like that.)

select * from something
where '2010-08-14' not between pay_period_start and pay_period_end
order by pay_period_start;

and I get

2010-08-15;2010-08-28
2010-08-29;2010-09-11

For pairs of dates, use the OVERLAPS operator. This query

select * from something
where 
  (date '2010-08-01', date '2010-08-14') overlaps 
  (pay_period_start,  pay_period_end) 
order by pay_period_start;

returns

2010-08-01;2010-08-14

To exclude rows where start order and end order exactly match a pay period, use something like this:

select * from something
where (
  (date '2010-08-01', date '2010-08-14') overlaps 
  (pay_period_start, pay_period_end)               and
  (date '2010-08-01' <> pay_period_start)          and
  (date '2010-08-14' <> pay_period_end)
)
order by pay_period_start;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号