I need to define a custom work week in MS access - ms-access-2016

I am trying to create a custom function on a form to define a week Number.
I have created a table that defines the week number.
Example WeekNo, StartDay, End Day
example: WeekNo 1 StartDay = 3/29/2020, End Day 4/4/2020
I have a Date box on my form if I enter a date of 3/29/2020
I would like 1 to be populated in my week number box.
On my form in the row source I have designed a Dlookup query
=DLookup("[WeekNumber]", "tblWeekNumber", "[Startdate] >= " & frmSearchNew.dt_Date & "") & [EndDate] <= frmSearchNew.dtDate
When I change to from view I get the error the record source specified on this form does not exist.
The table tblWeekNumber has the fields ID, WeekNo, StartDay and EndDay.
Where am I going wrong? any help is appreciated.

There are quite a few issues with the DLookup that you have put together.
Firstly, the field that you are looking for and the fields that you are using as criteria do not appear to match those in the table - WeekNumber/WeekNo, StartDate/StartDay, EndDate/EndDay;
Next, the logic for the lookup is wrong. You are trying to find a the week number that has a start date that is greater than the entered date, and an end date that is less than the entered date. What you should be looking for is a start date before the entered date, and an end date after the entered date.
Finally, dates are a bit funny in Access. You need to wrap them in '#' so that Access knows they are dates, and you should also take care to disambiguate them - 03/04/2020 could be either 3rd April or 4th March depending on you nationality.
Putting it all together, the final control source should look like:
=DLookUp("WeekNo","tblWeekNumber","StartDay<=#" & Format([dt_Date],"dd-mmm-yyyy") & "# AND EndDay>=#" & Format([dt_Date],"dd-mmm-yy") & "#")
Regards,

Related

Match date in two cells with conditional formatting, +/- 3 days.. Google sheets

I am making a deadline sheet for office.
I have made a conditional format that compares the dates with our "office are closed"-dates provided by our HR-department. If the delivery date match any of the "office closed"-dates in the next column it will be coloured red.
This works fine, but I just noticed one thing. If the date where 1 day before the holidays, and the holidays would be many days a row starting next day, we wouldn't see that and we would probably get big trouble manage Finnish these masters before deadline as we are not at office for a few days.
So, I thought, maybe I could add to the script something that says: "compare the dates in this column with the dates in "Office Closed"-column, if there is a match within a range of 5 days, color it red...?
Is this something I can do?
here is a screenshot of the sheet.
This is the code I use in Conditional Formatting now:
=COUNTIF($L$4:$L$25,H6)>0 which works fine.
Thanks for any help!
/Andreas
Use following formula in CF:
=IF(LEN(A2),SUMPRODUCT((($C$2:$C+3)>=A2)*(($C$2:$C-3)<=A2)))

Rails ActiveRecord - Select all objects by date, using only day, month, year, but ignoring the rest of the date's components

I have a model named Event. I want to be able to get all Events that were created at some specific date which should be something like this
Event.where(created_at: "20/01/2019".to_date)
The issue is that the created_at field also contains minutes, second, etc, which I want to ignore. I only want to compare the date by day, month and year. Is there any way I can acchieve that?
You can use Date#beginning_of_day and Date.end_of_day both provided by ActiveSupport core extensions.
d = '2019-01-20'.to_date
Event.where(created_at:(d.beginning_of_day..d.end_of_day))
This will not necessarily compare "...the date by day, month and year." but instead it will create a between clause that encompasses the entire day. If you want to use the Hash finder syntax this is probably the best way to go about it.
You could go with
Event.where(
Arel::Nodes::NamedFunction.new('CAST',
[Event.arel_table[:created_at].as('DATE')]
).eq(d)
)
If you really only want to compare the day, month and year.
Option 1 will result in
events.created_at BETWEEN '2019-01-20 00:00:00' AND '2019-01-20 23:59:59'
Option 2 will result in
CAST(events.created_at AS DATE) = '2019-01-20'

TABLEAU: calc field to get the last value available

I'm using Tableau Desktop, my data are like this:
KPI,date,monthValue
coffee break,01/06/2015,10.50
coffee break,01/07/2015,8.30
and I want to build a table like this
KPI, year(date), last value
coffee time, 2015, 8.30
How can I set a calculated field in order to show me the last value available in that year? I tried to do:
LOOKUP([MonthValue], LAST())
But it didn't work and tells me 'cannot mix aggregate and non-aggregate', so I did:
LOOKUP(sum([MonthValue]), LAST())
But it didn't work too. How should I proceed?
If you are using Tableau 9 then you can do this with an LOD calc that looks for the max value in your date field and then checks if the current date value is the same as the max date value.
[Date] == {fixed: max([Date])}
As you can see in the example below when you use the calc as a filter you will only get the last row from your example above.
UPDATE: to get the values per year you can do something like:
Here I am using a table calculation to find the max date per year and then ranking those dates and filtering down to the latest date in each year (which will be the one that has a rank equal to 1).
!max date is WINDOW_MAX(ATTR(Date))
!rank is RANK(Date)
You need to make sure that the table calculations are computer in the correct way (in this case across the values of each year).

grails ORM , how to search Date without time

I am using postrges db.
My domain has a date field:
java.util.Date requestedDate;
I am trying to search by date in my controller:
eq ("requestedDate", requestedDate)
This works fine, but the problem is that date and time has to be exactly matching for this. But in application the user will only enter the date to search items (like give me all requests which are made on 2014-02-05 and the browser application will add the current time to the request). So the comparison fails because the user entered time is different from the time during creation of the request.
I tried 'like' but it throws error.
How to compare only date part ?
You could do something like this:
Date now = new Date()
now.clearTime()
def results = Meeting.withCriteria {
between('date', now, now+1)
}
So this strips off the time portion of the current date, and then does a 'between' query (between midnight just gone and midnight 24 hours later).
Still it looks like there is no convenient way to realize this.
You need a small detour by computing the start of the day and the end of the day and use the between operator.
EDIT
I just saw now rcgeorge23 gave you the right example for doing this.

Store the day of the week and time?

I have a two-part question about storing days of the week and time in a database. I'm using Rails 4.0, Ruby 2.0.0, and Postgres.
I have certain events, and those events have a schedule. For the event "Skydiving", for example, I might have Tuesday and Wednesday and 3 pm.
Is there a way for me to store the record for Tuesday and Wednesday in one row or should I have two records?
What is the best way to store the day and time? Is there a way to store day of week and time (not datetime) or should these be separate columns? If they should be separate, how would I store the day of the week? I was thinking of storing them as integer values, 0 for Sunday, 1 for Monday, since that's how the wday method for the Time class does it.
Any suggestions would be super helpful.
Is there a way for me to store the the record for Tuesday and
Wednesday in one row or do should I have two records?
There are several ways to store multiple time ranges in a single row. #bma already provided a couple of them. That might be useful to save disk space with very simple time patterns. The clean, flexible and "normalized" approach is to store one row per time range.
What is the best way to store the day and time?
Use a timestamp (or timestamptz if multiple time zones may be involved). Pick an arbitrary "staging" week and just ignore the date part while using the day and time aspect of the timestamp. Simplest and fastest in my experience, and all date and time related sanity-checks are built-in automatically. I use a range starting with 1996-01-01 00:00 for several similar applications for two reasons:
The first 7 days of the week coincide with the day of the month (for sun = 7).
It's the most recent leap year (providing Feb. 29 for yearly patterns) at the same time.
Range type
Since you are actually dealing with time ranges (not just "day and time") I suggest to use the built-in range type tsrange (or tstzrange). A major advantage: you can use the arsenal of built-in Range Functions and Operators. Requires Postgres 9.2 or later.
For instance, you can have an exclusion constraint building on that (implemented internally by way of a fully functional GiST index that may provide additional benefit), to rule out overlapping time ranges. Consider this related answer for details:
Preventing adjacent/overlapping entries with EXCLUDE in PostgreSQL
For this particular exclusion constraint (no overlapping ranges per event), you need to include the integer column event_id in the constraint, so you need to install the additional module btree_gist. Install once per database with:
CREATE EXTENSION btree_gist; -- once per db
Or you can have one simple CHECK constraint to restrict the allowed time period using the "range is contained by" operator <#.
Could look like this:
CREATE TABLE event (event_id serial PRIMARY KEY, ...);
CREATE TABLE schedule (
event_id integer NOT NULL REFERENCES event(event_id)
ON DELETE CASCADE ON UPDATE CASCADE
, t_range tsrange
, PRIMARY KEY (event_id, t_range)
, CHECK (t_range <# '[1996-01-01 00:00, 1996-01-09 00:00)') -- restrict period
, EXCLUDE USING gist (event_id WITH =, t_range WITH &&) -- disallow overlap
);
For a weekly schedule use the first seven days, Mon-Sun, or whatever suits you. Monthly or yearly schedules in a similar fashion.
How to extract day of week, time, etc?
#CDub provided a module to deal with it on the Ruby end. I can't comment on that, but you can do everything in Postgres as well, with impeccable performance.
SELECT ts::time AS t_time -- get the time (practically no cost)
SELECT EXTRACT(DOW FROM ts) AS dow -- get day of week (very cheap)
Or in similar fashion for range types:
SELECT EXTRACT(DOW FROM lower(t_range)) AS dow_from -- day of week lower bound
, EXTRACT(DOW FROM upper(t_range)) AS dow_to -- same for upper
, lower(t_range)::time AS time_from -- start time
, upper(t_range)::time AS time_to -- end time
FROM schedule;
db<>fiddle here
Old sqliddle
ISODOW instead of DOW for EXTRACT() returns 7 instead of 0 for sundays. There is a long list of what you can extract.
This related answer demonstrates how to use range type operator to compute a total duration for time ranges (last chapter):
Calculate working hours between 2 dates in PostgreSQL
Check out the ice_cube gem (link).
It can create a schedule object for you which you can persist to your database. You need not create two separate records. For the second part, you can create schedule based on any rule and you need not worry on how that will be saved in the database. You can use the methods provided by the gem to get whatever information you want from the persisted schedule object.
Depending how complex your scheduling needs are, you might want to have a look at RFC 5545, the iCalendar scheduling data format, for ideas on how to store the data.
If you needs are pretty simple, than that is probably overkill. Postgresql has many functions to convert date and time to whatever format you need.
For a simple way to store relative dates and times, you could store the day of week as an integer as you suggested, and the time as a TIME datatype. If you can have multiple days of the week that are valid, you might want to use an ARRAY.
Eg.
ARRAY[2,3]::INTEGER[] = Tues, Wed as Day of Week
'15:00:00'::TIME = 3pm
[EDIT: Add some simple examples]
/* Custom the time and timetz range types */
CREATE TYPE timerange AS RANGE (subtype = time);
--drop table if exists schedule;
create table schedule (
event_id integer not null, /* should be an FK to "events" table */
day_of_week integer[],
time_of_day time,
time_range timerange,
recurring text CHECK (recurring IN ('DAILY','WEEKLY','MONTHLY','YEARLY'))
);
insert into schedule (event_id, day_of_week, time_of_day, time_range, recurring)
values
(1, ARRAY[1,2,3,4,5]::INTEGER[], '15:00:00'::TIME, NULL, 'WEEKLY'),
(2, ARRAY[6,0]::INTEGER[], NULL, '(08:00:00,17:00:00]'::timerange, 'WEEKLY');
select * from schedule;
event_id | day_of_week | time_of_day | time_range | recurring
----------+-------------+-------------+---------------------+-----------
1 | {1,2,3,4,5} | 15:00:00 | | WEEKLY
2 | {6,0} | | (08:00:00,17:00:00] | WEEKLY
The first entry could be read as: the event is valid at 3pm Mon - Fri, with this schedule occurring every week.
The second entry could be read as: the event is valid Saturday and Sunday between 8am and 5pm, occurring every week.
The custom range type "timerange" is used to denote the lower and upper boundaries of your time range.
The '(' means "inclusive", and the trailing ']' means "exclusive", or in other words "greater than or equal to 8am and less than 5pm".
Why not just store the datestamp then use the built in functionality for Date to get the day of the week?
2.0.0p247 :139 > Date.today
=> Sun, 10 Nov 2013
2.0.0p247 :140 > Date.today.strftime("%A")
=> "Sunday"
strftime sounds like it can do everything for you. Here are the specific docs for it.
Specifically for what you're talking about, it sounds like you'd need an Event table that has_many :schedules, where a Schedule would have a start_date timestamp...

Resources