I have created table with Employee, and I have columns such as Name, WorkingDays (datatype is date). I want to write a query that will output something like
"select Name from Employee where WorkingDay = 'monday', 'wednesday' and 'friday' "
i.e..I want to make a roaster for the workers. I am using sqlite and QT. thanks in advance.
As per Date And Time Functions documentation, you can use strftime function in this way:
SELECT Name FROM Employee WHERE strftime('%w',WorkingDay) IN ('1','3','5');
Where ('1','3','5') are ('Monday', 'Wednesday', 'Friday') respectively.
An off-topic note:
WorkingDays (datatype is date)
There's no such thing in SQLite. From Datatypes In SQLite Version 3 documentation:
1.2 Date and Time Datatype
SQLite does not have a storage class set aside for storing dates
and/or times. Instead, the built-in Date And Time Functions of SQLite
are capable of storing dates and times as TEXT, REAL, or INTEGER
values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic
Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Applications can chose to store dates and times in any of these
formats and freely convert between formats using the built-in date and
time functions.
Update
so that for example if today is friday, then automatically this name
appears on the names working today. Is it possible?
Yes it is. Just need to use strftime() function properly. I'll give you a little example:
CREATE TABLE Employee(
id INTEGER PRIMARY KEY,
name VARCHAR
);
CREATE TABLE WorkingDays(
id INTEGER PRIMARY KEY,
employee INTEGER,
dayNumber INTEGER,
FOREIGN KEY(employee) REFERENCES Employee(id),
UNIQUE(employee,dayNumer)
);
INSERT INTO Employee(name) VALUES('Max');
INSERT INTO Employee(name) VALUES('dic19');
INSERT INTO WorkingDays(employee,dayNumber) VALUES(1,1); --Max, Monday
INSERT INTO WorkingDays(employee,dayNumber) VALUES(1,2); --Max, Tuesday
INSERT INTO WorkingDays(employee,dayNumber) VALUES(1,3); --Max, Wednesday
INSERT INTO WorkingDays(employee,dayNumber) VALUES(2,4); --dic19, Thursday
INSERT INTO WorkingDays(employee,dayNumber) VALUES(2,5); --dic19, Friday
INSERT INTO WorkingDays(employee,dayNumber) VALUES(2,6); --dic19, Saturday
SELECT e.name
FROM WorkingDays w
LEFT JOIN Employee e ON w.employee = e.id
WHERE cast(w.dayNumber as text) = strftime('%w','now');
-- Right now it should return 'dic19' because Today is Friday/Saturday (depends on time zone)
SELECT e.name
FROM WorkingDays w
LEFT JOIN Employee e ON w.employee = e.id
WHERE cast(w.dayNumber as text) = strftime('%w','2013-11-11');
-- Should return 'Max' because '2013-11-11' was Monday
Related
I'm working on django api using a PostgreSQL database. The model has a date field representing a travel time (in jalali format) and an integer field representing number of passengers for that travel.
I'm using django_jalali to handle jalali date queries.
from django_jalali.db import models as jmodels
class TravelReport( models.Model ):
travel_date = jmodels.jDateField(verbose_name="تاریخ سفر")
passengers = models.IntegerField()
I want to aggregate sum of passengers for each week number in a jalali year. This is the query I'm using:
queryset= TravelReport.objects.annotate(week=F("travel_date__week")).values("week").annotate(total_passengers=Sum("passengers"))
Here is my problem: Django lookup __week is returning Georgian week number not jalali week number. For example week number for a travel date with jdatetime.date(1390, 5, 12) should be 19 but my query is returning 31.
What are my options to fix this?
Ok. Lets work out options:
override the lookup method to work using the jalali calender format.
convert your dates to gregorian format and store in another field, and call a function taht takes as input jalali format date, and sends the reciprocating gregorian format date to the lookup field.
Keep the number of passengers for a week stored in a separate field, with key as jalali calender weekname and value will be the number of passengers for that week.
I have a column called Snapshot Effective Period (next month) which is the Nextmonth([Snapshot Period]). This function stops when the snapshot period is 12/1/2021, what I expect to see is 1/1/2022 when the snapshot period is 12/1/2021. The value is not rolling over a year. Any advice?
Snapshot effective period next month c1 is a calculated column in date format.
Snapshot Effective Period (Next Month) c1 = NEXTMONTH('Forecast Detail'[Snapshot Period])
NEXTMONTH function should be used on Calendar
Notes In order to use any time intelligence calculation, you need a
well-formed date table. The Date table must satisfy the following
requirements:
All dates need to be present for the years required. The Date table
must always start on January 1 and end on December 31, including all
the days in this range. If the report only references fiscal years,
then the date table must include all the dates from the first to the
last day of a fiscal year. For example, if the fiscal year 2008 starts
on July 1, 2007, then the Date table must include all the days from
July 1, 2007 to June 30, 2008. There needs to be a column with a
DateTime or Date data type containing unique values. This column is
usually called Date. Even though the Date column is often used to
define relationships with other tables, this is not required. Still,
the Date column must contain unique values and should be referenced by
the Mark as Date Table feature. In case the column also contains a
time part, no time should be used – for example, the time should
always be 12:00 am. The Date table must be marked as a date table in
the model, in case the relationship between the Date table and any
other table is not based on the Date.
https://dax.guide/nextmonth/
Instead of NEXTMONTH use DATE
Snapshot Effective Period (Next Month) c1 = DATE( YEAR('Forecast Detail'[Snapshot Period]), MONTH('Forecast Detail'[Snapshot Period]) +1, DAY('Forecast Detail'[Snapshot Period]))
I have a field with a date in yyyy-MM-dd format, I want to extract the day only, for example, if the date is 2014-01-25, I want to have "25" in a new field. I used step "Calculator" is calculation "day of month of date A" but I get 1970-01-01 01:00:00 for all records.
Could someone tell me what might be the reason?
Before you actually have the Calculator step, have a Select Values step and make sure the date field is Date by explicitly giving the Date data type and specify the format it is currently in.
I have a requirement similar to this question, I need to store prices per date (prices change seasonally) and I have designed the bellow model:
room_calendar :
room_id :
date :
price:
I must store dates up ~one year then run a query to get all prices for x ranges of date and sum() all prices.
I think that approach is fine, but the downside is the volume of data in the database and the performance during queries when the database has many records.
I have another second approach in mind:
(calcul date at runtime) Yes I know! it may sound crazy
db model:
room_calendar :
room_id :
date_rule: <- store a dateutil rrule
price:
results:
{'room_id': {'dates': <dateutil.rrule.rrule object at 0x7fa2a8e3bda0>, 'price': 100}}
{'room_id': {'dates': <dateutil.rrule.rrule object at 0x7fa2a8e3bda0>, 'price': 150}}
Then:
dates_to_reserve = [datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3)]
room_price.objects.filter(date_rule__in=dates_to_reserve)
Of course I would have to create a custom field that supports store dateutil.rrule and when I query it with __in hit the __contains__ method of dateutil.rrule
sorry I can't express everything in a better way, SORRY FOR MY BAD ENGLISH
Do you have something better than the first approach?
Would there be any point in getting so involved with the second approach?
How would you do it? store each date or calcul it at runtime
EDIT
Thanks for your comment #iain-shelvington:
How complicated are the rules that affect the price and are they different for Each room?
Each rule is different for each room
A room has multiple rules
Each rule may be MONTHLY or WEEKLY, mainly
Can you give an example of a room, it's base price and the eventual price for each date?
Ej.:
Room standard > price: 150 > date_rule: from Jan 2020 weekly on weekdays until Feb 25 2020
Room standard > price: 170 > date_rule: from Jan 2020 weekly on weekends until Feb 25 2020
Room standard > price: 180 > date_rule: from Feb 2020 weekly on weekends until May 26 2020
I have developed a dateutil.rrule based application that correctly handles even more complex rules, so the rules would not be a problem.
Writing an efficient algorithm that calculates prices by date at runtime would be the problem
thanks
I use dateutil.rrrule for a task manager application. I store it in a varchar field and then have functions in the database written in plpythonu3 that can expand that value on demand. That is one way to go.
One example of such a function is:
CREATE OR REPLACE FUNCTION public.task_occurrences(t_rrule character varying, start_dt timestamp with time zone, end_dt timestamp with time zone)
RETURNS timestamp with time zone
LANGUAGE plpython3u
SECURITY DEFINER
AS $function$
from datetime import datetime
from dateutil.parser import parse
from dateutil.rrule import rrulestr
rule = rrulestr(t_rrule, ignoretz=True)
next_occ = rule.between(parse(start_dt, ignoretz=True),
parse(end_dt, ignoretz=True), inc=True, count=1)
if next_occ:
return next_occ[0]
else:
return None
$function$
;
This finds the first occurrence of a task in a date range or returns None/NULL if there is not one.
Another option would be to store the seasonal prices in a separate table that has start and end dates for the season and the associated price. You could use Postgres date range math range types, range operators to join that table to a room date to fetch the appropriate price.
Example:
CREATE TABLE seasonal_price(id serial, start_date date, end_date date, price numeric);
SELECT price FROM seasonal_price, room_calendar WHERE room_calendar.date <# daterange(start_date, end_date, '[]');
Price calculation rules tend to change, so I would refrain from hard coding them in the database.
Rather than storing the price for each day, use the daterange type to persist the price for a whole range of dates.
I've a requirement where I need to compare a column date with current date. If my column date > last sunday's date I need to populate a status. Here, am facing issues in calculating present week's sunday date.
I need to calculate Previous Sunday's date in Informatica expression transformation.
I am not exactly sure about your requirement, however, you can always get the day and based on that subtract a fixed number of days to reach any sunday you want (present week or previous week). You should have a limited (7) set of IIF statements to achieve this.
Eg. If the day is 'Tuesday' (day of the current date) then subtract 2 from the date to get sunday date!
You can write an expression as- trunc(sysdate,'d') in a variable port which is having datatype as date.
The expression would return the Sunday date of the current date. Then you can compare the two dates (your column date and the variable port date) and populate the status.
If you just want to verify the result of the expression trunc(sysdate,'d') you can fire the following query in the oracle db:
"select trunc(sysdate,'d') from dual"
result returned would be the latest Sunday date.