I would like to get the following dates in Impala query:
a. Sunday to Saturday Week (SSW):
1. First and Last day of Current week (SSW)
2. First and Last day of Previous week(SSW)
b. Monday to Sunday Week (MSW):
1. First and Last day of Current week (MSW)
2. First and Last day of Previous week(MSW)
c. Month:
1. First and Last Day of Current Month
2. First and Last Day of Previous Month
d. Quarter:
1. First and Last Day of Current Quarter
2. First and Last Day of Previous Quarter
e. Year:
1. First and Last Day of Current Year
2. First and Last Day of Previous Year
This is what I have so far:
SELECT
--Month
date_add(last_day(add_months(current_timestamp(),-1)),1) as Frist_Day_of_Current_Month,
last_day(now()) as Last_Day_of_Current_Month,
date_add(last_day(add_months(current_timestamp(),-2)),1) as Frist_Day_of_Previous_Month,
last_day(add_months(current_timestamp(),-1)) as Last_Day_of_Previous_Month,
--Year
trunc(now(), 'Y') as Frist_Day_of_Current_Year,
date_sub(trunc(now(), 'YEAR'), 1) AS Last_Day_of_Previous_Year
Here are the dates:
SELECT
--SINGLE DAYS
TRUNC(NOW(),'DD') AS TODAY,
ADDDATE(TRUNC(NOW(),'DD'), -1) AS YESTERDAY,
ADDDATE(TRUNC(NOW(),'DD'), -2) AS TWO_DAYS_AGO,
ADDDATE(TRUNC(NOW(),'DD'), -3) AS THREE_DAYS_AGO,
ADDDATE(TRUNC(NOW(),'DD'), -4) AS FOUR_DAYS_AGO,
ADDDATE(TRUNC(NOW(),'DD'), -5) AS FIVE_DAYS_AGO,
ADDDATE(TRUNC(NOW(),'DD'), -6) AS SIX_DAYS_AGO,
ADDDATE(TRUNC(NOW(),'DD'), -7) AS WEEK_AGO,
--WEEK
--SUNDAY TO SATURDAY (NEED TO SCHEDULE THE REPORT TO RUN ON ONLY ON MONDAYS)
TRUNC(NOW(), 'D') - INTERVAL 1 DAY AS FIRST_DAY_OF_CURRENT_WEEK_SS,
TRUNC(NOW(), 'D') + INTERVAL 5 DAY AS LAST_DAY_OF_CURRENT_WEEK_SS,
TRUNC(NOW(), 'D') - INTERVAL 8 DAY AS FIRST_DAY_OF_PREVIOUS_WEEK_SS,
TRUNC(NOW(), 'D') - INTERVAL 2 DAY AS LAST_DAY_OF_PREVIOUS_WEEK_SS,
--MONDAY TO SUNDAY (NEED TO SCHEDULE THE REPORT TO RUN ONLY ON MONDAYS)
TRUNC(NOW(),'DY') AS FRIST_DAY_OF_CURRENT_WEEK_MS,
TRUNC(NOW(),'DY') + INTERVAL 6 DAY AS LAST_DAY_OF_CURRENT_WEEK_MS,
TRUNC(NOW(),'DY') - INTERVAL 7 DAY AS FIRST_DAY_OF_PREVIOUS_WEEK_MS,
TRUNC(NOW(),'DY') - INTERVAL 1 DAY AS LAST_DAY_OF_PREVIOUS_WEEK_MS,
--MONTH
DATE_ADD(LAST_DAY(ADD_MONTHS(CURRENT_TIMESTAMP(),-1)),1) AS FRIST_DAY_OF_CURRENT_MONTH,
LAST_DAY(NOW()) AS LAST_DAY_OF_CURRENT_MONTH,
DATE_ADD(LAST_DAY(ADD_MONTHS(CURRENT_TIMESTAMP(),-2)),1) AS FRIST_DAY_OF_PREVIOUS_MONTH,
LAST_DAY(ADD_MONTHS(CURRENT_TIMESTAMP(),-1)) AS LAST_DAY_OF_PREVIOUS_MONTH,
--QUARTER
TRUNC(NOW(), 'Q') AS FIRST_DAY_OF_CURRENT_QUARTER,
TRUNC(NOW(), 'Q')+ INTERVAL 3 MONTHS - INTERVAL 1 DAY AS LAST_DAY_OF_CURRENT_QUARTER,
TRUNC(NOW(), 'Q') - INTERVAL 3 MONTHS AS FIRST_DAY_OF_PREVIOUS_QUARTER,
TRUNC(NOW(), 'Q') - INTERVAL 1 DAY AS LAST_DAY_OF_PREVIOUS_QUARTER,
--YEAR
TRUNC(NOW(), 'Y') AS FRIST_DAY_OF_CURRENT_YEAR,
TRUNC(NOW(), 'YEAR') + INTERVAL 1 YEAR - INTERVAL 1 DAY AS LAST_DAY_OF_CURRENT_YEAR,
TRUNC(NOW(), 'YEAR') - INTERVAL 1 YEAR AS FRIST_DAY_OF_PREVIOUS_YEAR,
TRUNC(NOW(), 'Y') - INTERVAL 1 DAY AS LAST_DAY_OF_PREVIOUS_YEAR
Thanks,
Regards,
Ahmed
Here I share the query I was looking for :)
TRUNC(add_months(NOW() ,-3), 'Q') - INTERVAL 1 DAY AS LAST_DAY_OF_PREVIOUS_QUARTER_-2
Related
I need to sum value by date range in multiple columns. Every date range is one week of a month. It can be shorter than 7 days if it is the start of the month or the end of the month.
For example, I have dates for February:
my_user my_date my_value
A 01.02.2019 100
A 02.02.2019 150
B 01.02.2019 90
Z 28.02.2019 120
How can I have in date range format such as below?
my_user 01/02-03/02 04/02-10/02 11/02-17/02 18/02-24/02 25/02-28/02
A 250 0 0 0 0
B 90 0 0 0 0
Z 0 0 0 0 120
Any suggestions? Thanks!
You can do this:
select *
from (
select to_char(dt, 'iw') - to_char(trunc(dt, 'month'), 'iw') + 1 wk, usr, val from t)
pivot (sum(val) for wk in (1, 2, 3, 4, 5, 6))
demo
USR 1 2 3 4 5 6
--- ---------- ---------- ---------- ---------- ---------- ----------
A 250
B 90
Z 120
Header numbers are the weeks of month. Maximum may be 6 if month starts at the end of the week and is longer than 28 days.
Similiar way you can find first and last day of each week if needed, but you can't put them as headers, or at least not easily.
Edit:
it is possible to define certain date range with pivot, simple as two
dates? For example, I need to sum values from 5 December 2018 to 4
January 2019, 5 January 2019 to 4 February 2019, 5 March 2019 to 4
April 2019
Yes. Everything depends on how we count first and next weeks. Here:
to_char(dt, 'iw') - to_char(trunc(dt, 'month'), 'iw') + 1
i am subtracting week in year for given date and week in year of first day in month for this date. You can simply replace this second value with your starting date, either by hardcoding it in your query or by sending parameter to query or finding minimum date at first in a subquery:
(to_char(dt, 'iw') - to_char(date '2019-03-05', 'iw')) + 1
or
(to_char(dt, 'iw') - to_char((select min(dt) from data), 'iw')) + 1
Edit 2:
There is one problem however. When user defined period contains two or more years. to_date(..., 'iw') works fine for one year, but for two we get values 51, 52, 01, 02... We have to deal with this somehow, for instance like here:
with t(dt1, dt2) as (select date '2018-12-16', date '2019-01-15' from dual)
select min(dt) mnd, max(dt) mxd, iw, row_number() over (order by min(dt)) rn
from (select dt1 + level - 1 dt, to_char(dt1 + level - 1, 'iw') iw
from t connect by level -1 <= dt2 - dt1)
group by iw
which gives us:
MND MXD IW RN
----------- ----------- -- ----------
2018-12-16 2018-12-16 50 1
2018-12-17 2018-12-23 51 2
2018-12-24 2018-12-30 52 3
2018-12-31 2019-01-06 01 4
2019-01-07 2019-01-13 02 5
2019-01-14 2019-01-15 03 6
In first line we have user defined date ranges. Then I did hierarchical query looping through all dates in range assigning week, then grouped by this week, found start and end dates for each week and assigned row number rn which can be further used by pivot.
You can now simply join your input data with this query, let's name it weeks:
from data join weeks on dt between mnd and mxd
and make pivot. But for longer periods you have to find how many weeks there can be and specify them in pivot clause in (1, 2, 3, 4...). You can also add aliases if you need:
pivot ... for rn in (1 week01, 2 week02... 12 week12)
There is no simply way to avoid listing them manually. If you need it please look for oracle dynamic pivot in SO, there where hundreds similiar questions already. ;-)
I have a requirement to obtain number of days passed since creation date. This number would need to minus the weekends. I have only some functions : JulianDay, JulianWeek, JulianYear to get Julian date values, I also have Today which returns the date of today, time stamp which returns date and time. I have manage to get the difference of today-creation date by using: JulianDay(today)-JulianDay(creation date) but I still can't wrap my head around subtracting the weekends
Not completely sure what the functions you cited in your question do, however, you seem to be comfortable with
doing the basic date arithmetic to determine the number of days between two given dates. The hard part seems
to be figuring out how may days to subtract for weekends.
I think you can accomplish this with two functions:
Given two dates, return the number of days between them. Call this DAYS(date-1, date-2)
Given a date, return the day of the week (where 1 = Monday ... 7 = Sunday). Call this DAY-OF-WEEK(date)
Having these functions you can then do the following:
Calculate full weeks in the date range: WEEKS = DAYS(date-1, date2) mod 7
Calculate days not parts of full weeks: DAYS-LEFT = DAYS(date-1, date-2) - (WEEKS * 7)
Determine which day of the week the last day falls on: LAST-DAY = DAY-OF-WEEK(date-2)
Adjust the number of DAYS-LEFT from the partial week as follows:
if DAYS-LEFT > 0 then
case LAST-DAY
when 6 then /* Saturday */
DAYS-LEFT = DAYS-LEFT - 1
when 7 then /* Sunday */
if DAYS-LEFT = 1 then
DAYS-LEFT = 0
else
DAYS-LEFT = DAYS-LEFT - 2
end-if
when other /* Monday through Friday */
case DAYS-LEFT - LAST-DAY
when > 1 then
DAYS-LEFT = DAYS-LEFT - 2
when = 1 then
DAYS-LEFT = DAYS-LEFT - 1
when other
DAYS-LEFT = DAYS-LEFT /* no adjustment */
end-case
end-case
end-if
DAYS-EXCLUDING-WEEKENDS = DAYS(date-1, date-2) - (WEEKS * 2) + DAYS-LEFT
I assume you have, or can build, a DAYS(date-1, date-2) function. The next bit is to determine what day of the week
a given date falls on. The algorithm to do this is called Zeller's congruence. I won't
repeat the algorithm here since Wikipedia does a fine job of describing it.
Hope this gets you on your way...
Your JulianDay(y,m,d) function returns a serial number for each date; let's say for the sake of discussion that JulianDay(2013,7,4) returns 2456478. The next day will be 2456479, then 2456480, and so on. And let's say that the difference of two days is diff.
The number of full weeks in diff, each containing 5 weekdays, is diff // 7 (that's integer division, so it rounds down). Thus if diff is 25, there will be 25 // 7 = 3 full weeks plus an extra diff % 7 = 4 days. The 3 full weeks contain 15 weekdays; it doesn't matter which day of the week you start from. So you only need to consider the 4 extra days to see how may are weekdays.
The number that the JulianDay function returns can be taken modulo 7 to calculate the day of the week; on my JulianDay function, modulo 5 represents Saturday and modulo 6 represents Sunday. You can take the 4 extra days to be either the 4 days at the beginning of the period or the 4 days at the end; it doesn't matter because all the other days are part of a period of consecutive full weeks that each have 5 weekdays. Say you pick the first 4 days. Then take the JulianDay of the first day modulo 7, then the JulianDay of the first day plus 1 modulo 7, then the JulianDay of the first day plus 2 modulo 7, then the JulianDay of the first day plus 3 modulo 7, determine how many of them are weekdays, and add that to the number of weekdays in full weeks.
All you need is a JulianDay function.
This code should do what you want:
Date fromDate = new Date(System.currentTimeMillis()-(30L*24*60*60*1000)); // 30 days ago
Date toDate = new Date(System.currentTimeMillis()); // now
Calendar cal = Calendar.getInstance();
cal.setTime(fromDate);
int countDays = 0;
while (toDate.compareTo(cal.getTime()) > 0) {
if (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY)
countDays++;
cal.add(Calendar.DATE, 1);
}
System.out.println(countDays);
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have deviced a procedure to find nth working day without using loops.
Please bring around your suggesstions over this -
Algorithm to manipulate working days -
Problem: Find the date of nth working day from any particular day.
Solution:
Normalize to closest Monday -
If today(or the initial day) happens to be something other than monday, bring the day to the closest monday by simple addition or subtraction.
eg: Initial Day - 17, Oct. This happens to be wednesday. So normalize this no monday by going 2 dates down.
Now name this 2 dates, the initial normalization factor.
Add the number of working days + week ends that fall in these weeks.
eg: to add 10 working days, we need to add 12 days. Since 10 days has 1 week that includes only 1 saturday and 1 sunday.
this is because, we are normalizing to nearest monday.
Amortizing back -
Now from the end date add the initial normalization factor (for negative initial normalization) and another constant factor (say, k).
Or add 1 if the initial normalization is obtained from a Friday, which happens to be +3.
If start date falls on Saturday and sunday , treat as monday. so no amortization required at this step.
eg: Say if initial normalization is from wednesday, the intial normalization factor is -2. Hence add 2 to the end date and a constant k.
The constant k is either 2 or 0.
Constant definition -
If initial normalization factor is -3, then add 2 to the resulting date if the day before amortization is (wed,thu,fri)
If initial normalization factor is -2, then add 2 to the resulting date if the day before amortization is (thu,fri)
If initial normalization factor is -1, then add 2 to the resulting date if the day before amortization is (fri)
Example -
Find the 15th working day from Oct,17 (wednesday).
Step 1 -
initial normalization = -2
now start date is Oct,15 (monday).
Step 2 -
add 15 working days -
15 days => 2 weeks
weekends = 2 (2 sat, 2 sun)
so add 15 + 4 = 19 days to Oct, 15 monday.
end_date = 2, nov, Friday
Step 3a -
end_date = end_date + initial normalization = 4, nov sunday
Step 3b -
end_date = end_date + constant_factor = 4, nov, sunday + 2 = 6, nov (Tuesday)
Cross Verfication -
Add 15th working day to Oct, 17 wednesday
Oct,17 + 3 (Oct 17,18,19) + 5 (Oct 22-26) + 5 (Oct 29 - Nov 2) + 2 (Nov 5, Nov 6)
Now the answer is 6, Nov, Tuesday.
I have verified with a few cases. Please share your suggesstions.
Larsen.
To start with, its a nice algorithm, i have doubts about boundary conditions though: for example, what if i need to find the 0th working day from today's date:
Step 1 -
initial normalization = -2 now start date is Oct,15 (monday).
Step 2 -
add 0 working days -
0 days => 0 weeks
weekends = 0
so add 0 + 0 = 0 days to Oct, 15 monday.
end_date = 15, oct, monday
Step 3a -
end_date = end_date + initial normalization = 17, oct wednesday
Step 3b -
end_date = end_date + constant_factor = 17, Oct wednesday or 19,oct friday based on whether constant factor is 0 or 2 as it be only one of these values.
Now lets repeat the steps for finding the 1st working day from today:
Step 1 -
initial normalization = -2 now start date is Oct,15 (monday).
Step 2 -
add 1 working days -
1 days => 0 weeks
weekends = 0
so add 1 + 0 = 1 days to Oct, 15 monday.
end_date = 15, oct, monday
Step 3a -
end_date = end_date + initial normalization = 17, oct wednesday
Step 3b -
end_date = end_date + constant_factor = 17, Oct wednesday or 19,oct friday based on whether constant factor is 0 or 2 as it be only one of these values.
Did you notice, algorithm gives the same end result for 0 and 1. May be thats not an issue if t defined beforehand that 0 working days and 1 working days are considered as same scenario, but ideally they should be giving different results.
I would also suggest you to consider the negative test cases, like what if i need to find -6th working day from today, will your alforithm give me a date in past rightfully?
Lets consider 0th working day from today (17/10, wed).
Step 1 -
start_date = 17/10 wed
normalized date = 15/10 mon
Step 2 -
end_date = normalized date + working days
= 15/10 mon + 0 = 15/10 mon
Step 3 -
amortized_back = end_date_before_amortization + normalization factor
= 15/10 + (+2) = 17/10 wed
since the end_date_before_amortization falls on monday and initial normalization is 2, constant factor = 0.
hence, end_date = 17/10 wed.
now case 2, 1st working day from today.
Step 1 -
start_date = 17/10 wed
normalized date = 15/10 mon
Step 2 -
end_date = normalized date + working days
= 15/10 mon + 1 = 16/10 tue
Step 3 -
amortized_back = end_date_before_amortization + normalization factor
= 16/10 + (+2) = 18/10 thu.
since the end_date_before_amortization falls on tuesday and initial normalization is 2, constant factor = 0.
hence, end_date = 18/10 thu.
Looks to be working for 0th and 1st WD.
Using Ruby how can you determine if the coming Sunday is the first, second or third Sunday of the month?
#ElYusubov - is close, but not quite right.
As a starting point, the division must be by seven (number of days in a week). But time.day gives a day-of-the-month from 1 to 31, so first you need to subtract one before the division and add one after. The first eight days of any month give...
Day number (Day# - 1) / 7 Week#
---------- -------------- -----
1 0.0 1
2 0.14 1
3 0.29 1
4 0.43 1
5 0.57 1
6 0.71 1
7 0.86 1
8 1 2
Whichever day-of-the-week time.day gives, that week# indicates whether it's the first, second etc of that day-of-the-week. But you want the coming Sunday.
wday gives a weekday - 0 to 6, with 0 meaning Sunday. So how many days are there to the coming Sunday? Well, that depends on your definition of "Coming", but if you exclude today==Sunday, you basically subtract todays weekday from 7.
Weekday today Days until next Sunday
------------- ----------------------
0 (Sun) 7
1 (Mon) 6
2 (Tue) 5
3 (Wed) 4
4 (Thu) 3
5 (Fri) 2
6 (Sat) 1
If you allow the "coming" Sunday to be today, then you do the same thing but replace seven with zero. You can either do a conditional check, or use the modulo/remainder operator.
Anyway, once you know how many days ahead the coming Sunday is, you can calculate the date value for that (add those days to todays date) and then determine the week number in the month for that date instead of today using the first method (subtract 1, divide by seven, add 1).
Relevant vocabulary...
Date.wday 0 to 6 (0 = sunday)
Date.day 1 to 31
I won't try to provide the code because I don't know Ruby.
I'm looking for the cleverest algorithm for determining the number of fortnightly occurring events in a given calendar month, within a specific series.
i.e. Given the series is 'Every 2nd Thursday from 7 October 2010' the "events" are falling on (7 Oct 2010, 21 Oct, 4 Nov, 18 Nov, 2 Dec, 16 Dec, 30 Dec, ...)
So what I am after is a function
function(seriesDefinition, month) -> integer
where:
- seriesDefinition is some date that is a valid date in the series,
- month indicates a month and a year
such that it accurately yeilds: numberFortnightlyEventsInSeriesThatFallInCalendarMonth
Examples:
NumberFortnightlyEventsInMonth('7 Oct 2010, 'Oct 2010') -> 2
NumberFortnightlyEventsInMonth('7 Oct 2010, 'Nov2010') -> 2
NumberFortnightlyEventsInMonth('7 Oct 2010, 'Dec 2010') -> 3
Note that October has 2 events, November has 2 events, but December has 3 events.
Psuedocode preferred.
I don't want to rely on lookup tables or web service calls or any other external resources other than potentially universal libraries. For example, I think we can safely assume that most programming languages will have some date manipulation functions available.
There is no "clever" algorithm when handling dates, there is only the tedious one. That is, you have to specifically list how many days are in each month, handle leap years (every four years, except every 100 years, except every 400 years), etc.
Well, for the algorithm you are talking about the usual solution is to calculate the day number starting from some fixed date. (Number of day plus cumulated number of days in prev months plus number of years * 365 minus (number of year / 4) plus (number of year / 100) minus (number of year / 400))
Having this, you can easily implement what you need to. You need to calculate which day of week was the 1 January 1. Then you can easily see what is the number of "every second thursdays" from that day to 1 Oct 2010 and 1 Dec 2010. their difference is the value you are looking for.
My solution ...
Public Function NumberFortnightlyEventsInMonth(seriesDefinition As Date, month As String) As Integer
Dim monthBeginDate As Date
monthBeginDate = DateValue("1 " + month)
Dim lastDateOfMonth As Date
lastDateOfMonth = DateAdd("d", -1, DateAdd("m", 1, monthBeginDate))
' Step 1 - How many days between seriesDefinition and the 1st of [month]
Dim daysToMonthBegin As Integer
daysToMonthBegin = DateDiff("d", seriesDefinition, monthBeginDate)
' Step 2 - How many fortnights (14 days) fit into the number from Step 1? Round up to the nearest whole number.
Dim numberFortnightsToFirstOccurenceOfSeriesInMonth As Integer
numberFortnightsToFirstOccurenceOfSeriesInMonth = (daysToMonthBegin \ 14) + IIf(daysToMonthBegin Mod 14 > 0, 1, 0)
' Step 3 - The date of the first date of this series inside that month is seriesDefinition + the number of fortnights from Step 2
Dim firstDateOfSeriesInMonth As Date
firstDateOfSeriesInMonth = DateAdd("d", (14 * numberFortnightsToFirstOccurenceOfSeriesInMonth), seriesDefinition)
' Step 4 - How many fortnights fit between the date from Step 3 and the last date of the [month]?
NumberFortnightlyEventsInMonth = 1 + (DateDiff("d", firstDateOfSeriesInMonth, lastDateOfMonth) \ 14)
End Function