Date time functions help informix - sql

How can I use the date add or date diff functions I have a scenario where I need find people whose birthdays are either today or after n number of days. How can I achieve it in informix.
SELECT mbr_code, fname, lname
INTO rsMbrCode, rsFName, rsLName
FROM asamembr
WHERE cust_code = membershipnumber
AND ((day(bdate) - day(CURRENT)) <= rsTest
AND MONTH(bdate) = month(CURRENT))
RETURN rsMbrCode, rsFName, rsLName WITH RESUME;

You could do something like this:
SELECT mbr_code,fname,lname
INTO rsMbrCode,rsFName,rsLName
FROM asamembr
WHERE cust_code = membershipnumber
AND MDY(month(bdate),day(bdate),year(today))
BETWEEN TODAY AND TODAY + <NUMBEROFDAYS> UNITS DAY;
You construct a date with Using MDY with the MONTH and DAY from bdate and YEAR from TODAY. Then you see if it is between the dates you want to match.
Documentation for MDY:
The MDY function takes as its arguments three integer expressions that
represent the month, day, and year, and returns a type DATE value.
The first argument represents the number of the month (1 to 12).
The second argument represents the number of the day of the month (1 to 28, 29, 30, or 31, as appropriate for the month)
The third expression represents the 4-digit year. You cannot use a 2-digit abbreviation.

Related

How to get the data for the last 12 months and split and month-wise in HIVE?

Table format for the date column is "yyyyMMdd" and I'm using the following functions to convert into standard format so that HIVE day, months and year can be performed to get the respective values.
(from_unixtime(unix_timestamp(cast(created_day as STRING) ,'yyyyMMdd'), 'yyyy-MM-dd'))
To get the current year data, I would subtract the year obtained from all the records with the year returned by the current date and if it return zero, then it falls in this year.
(year(current_date()) - year(from_unixtime(unix_timestamp(cast(created_day as STRING) ,'yyyyMMdd'), 'yyyy-MM-dd'))) = 0
Problem: If the current date falls in January, I would get only January data month, but i need to get the data from February(last year) to January(current year)?
Also I need to scale this to obtain the last 24 months.
I always set my date range parameters outside of Hive and pass them as arguments as this lends itself to reproducibility and testability.
select <fields> from <table> where created_day between ${hiveconf:start_day} and ${hiveconf:end_day}

MS SQL How to get the next month if its december

Hi I wanna get the next month in SQL server but what if the month is 12.
when i have date = '2016-10-04' then the next month will be date = '2016-11-04'.
I want to put this into this query :
if EXISTS(
select * from month
where id_Prod = #id_Prod
and datepart(month,DATEADD(month,1,_date)) = datepart(month,DATEADD(month,1,_date))
and datepart(YEAR,_date) = datepart(YEAR,#date)
);
you can try dateadd
declare #dt date = getdate()
select datepart(MM,dateadd(mm,1, #dt))
If the spec I've given in the comments is correct, you want something along the lines of:
if EXISTS(
select * from month
where id_Prod = #id_Prod
and _date >= DATEADD(month,DATEDIFF(month,'20010101',#date),'20010201')
and _date < DATEADD(month,DATEDIFF(month,'20010101',#date),'20010301')
);
The DATEADD,DATEDIFF pairs are just being used to generate "the 1st of next month" and "the 1st of the month after that", using arbitrary (fixed) dates to compute those. E.g. the first line computes how many whole months have occurred between 1st January 2001 and #date. It then adds that number of months onto 1st February 2001. This expression should therefore always generate the 1st of the month that comes after #date. The second pair does the same but adds the computed number onto 1st March instead.
You should also note that I'm not applying any functions to _date, so if there happens to be a useful index on that column, it should be usable for this query.
This seems pretty simple,
Get Previous date of current date
SELECT DATEADD(MONTH,-1,GETDATE()) AS PrviousDate
Get Next date of current date
SELECT DATEADD(MONTH,1,GETDATE()) AS NextDate

How to calculate ages in BigQuery?

I have two TIMESTAMP columns in my table: customer_birthday and purchase_date. I want to create a query to show the number of purchases by customer age, to create a chart.
But how do I calculate ages, in years, using BigQuery? In other words, how do I get the difference in years between two TIMESTAMPs? The age calculation cannot be made using days or hours, because of leap years, so the function DATEDIFF(<timestamp1>,<timestamp2>) is not appropriate.
Thanks.
First of all, I'd really love BigQuery to have a function which calculates current age based on a date. That seems to be like a very common use case and it's not really easy due to the whole leap year thing.
I found a great article about this issue: https://towardsdatascience.com/how-to-accurately-calculate-age-in-bigquery-999a8417e973
Their final approach is similar to Lars Haugseth's and Saad's answer, but they do not use the DAYOFYEAR part in order to avoid issues with leap years. It also gives you the flexibility not only to calculate the current age, but also the age at a particular date that you pass to the function as argument:
CREATE OR REPLACE FUNCTION workspace.age_calculation(as_of_date DATE, date_of_birth DATE)
AS (
DATE_DIFF(as_of_date,date_of_birth, YEAR) -
IF(EXTRACT(MONTH FROM date_of_birth)*100 + EXTRACT(DAY FROM date_of_birth) >
EXTRACT(MONTH FROM as_of_date)*100 + EXTRACT(DAY FROM as_of_date)
,1,0)
)
Regarding the difference between dates - you could consider user-defined functions (https://cloud.google.com/bigquery/user-defined-functions) with a JavaScript date library, such as Datejs or Moment.js
You can use DATE_DIFF to get the difference in years, but need to subtract by one if the birthday has not yet occured this year:
IF(EXTRACT(DAYOFYEAR FROM CURRENT_DATE) < EXTRACT(DAYOFYEAR FROM birthdate),
DATE_DIFF(CURRENT_DATE, birthdate, YEAR) - 1,
DATE_DIFF(CURRENT_DATE, birthdate, YEAR)) AS age
Here it is in a user defined function:
CREATE TEMP FUNCTION calculateAge(birthdate DATE) AS (
DATE_DIFF(CURRENT_DATE, birthdate, YEAR) +
IF(EXTRACT(DAYOFYEAR FROM CURRENT_DATE) < EXTRACT(DAYOFYEAR FROM birthdate), -1, 0) -- subtract 1 if bithdate has not yet occured this year
);
You can compute the number of days it would be if all years were 365 days long, take the difference, and divide by 365. For example:
SELECT (day2-day1)/365
FROM (
SELECT YEAR(t1) * 365 + DAYOFYEAR(t1) as day1,
YEAR(t2) * 365 + DAYOFYEAR(t2) as day2
FROM (
SELECT TIMESTAMP('20000201') as t1,
TIMESTAMP('20140201') as t2))
This returns 14.0, even though there are intervening leap years. If you want the final result as an integer instead of floating point, you can use the INTEGER() function to cast the result.
Note that if one of the dates is a leap day (feb 29) it will appear to be one year away from march 1, but I think this sounds like the intended behavior.
Another way to calculate age that takes leap years into account is to:
Calculate simple age based on difference in year
Either subtract 1 or not by:
Add difference in years to birthday (e.g. if today is 2022-12-14 and birthday is 2000-12-30, then the "new" birthday becomes 2022-12-30)
Do a DAY-based difference between today and "new" birthday, which either gives you a positive number (birthday passed for this year) or negative number (still has birthday this year)
Subtract 1 year from simple age calculation if number is negative
In BigQuery SQL code this looks like:
SELECT
bd AS birthday
,today
,DATE_DIFF(today, bd, YEAR) AS simpleAge
,DATE_DIFF(today, bd, YEAR) +
(CASE
WHEN DATE_DIFF(today, DATE_ADD(bd, INTERVAL DATE_DIFF(today, bd, YEAR) YEAR), DAY) >= 0
THEN 0
ELSE -1
END) AS age
FROM
(SELECT
PARSE_DATE("%Y-%m-%d", "2000-12-01") AS bd
,CURRENT_DATE("Asia/Tokyo") AS today
)
Outputs:
birthday
today
simpleAge
age
2000-12-30
2022-12-14
22
21

How to get the difference between two dates (informix)?

How to get the difference between two dates (informix) in integer format like that
day = 15
mon = 2
year = 1
There are two sets of date/time values in Informix: DATE and DATETIME.
The DATE type is oldest (it was in the precursor to the SQL-based Informix), and represents the integer number of days since a reference date (where day 0 is 1899-12-31, so day 1 was 1900-01-01).
You get the difference between two DATE values in days by subtracting one from the other.
The DATETIME system is newer (but still old — circa 1990). You can take the difference between two DATETIME YEAR TO DAY values and get a result that is an INTERVAL DAY TO DAY (essentially the number of days).
You could also take the difference between two DATETIME YEAR TO MONTH values and get a result that is an INTERVAL YEAR TO MONTH.
However, there is no way to get a difference in years, months and days because there is no simple way to deduce that value. In fact, ISO SQL recognizes two classes of INTERVAL: those in the YEAR-MONTH group, and those in the DAY-SECOND group. You can't have an INTERVAL that crosses the MONTH/DAY barrier.
Use the MDY function :
select mdy(2,15,2014) - mdy(1,15,2014) from sysmaster:sysdual

Determining if a leap day falls between two days with DB2 SQL

I have a table with two dates, "Start_Date" and "End_Date". In DB2 SQL, is there a way to determine if a leap day falls between these two dates?
Thank you!
Sure, you can do this using some date math and the DAYS function, by comparing the number of days between the the start and end date to the number of days between the start date and end date when they've both been shifted by 1 year.
If the number of days between the two dates is the same in both cases, then no leap day has occurred. If the number of days differs, then there has been at least 1 leap day.
This expression will return the number of leap days:
select
( DAYS(end_date + 1 year) - DAYS(start_date + 1 year) ) -
( DAYS(end_date) - DAYS(start_date) )
from
sysibm.sysdummy1
This should work as long as end_date >= start_date.
It's trivial to encapsulate this into a scalar User Defined Function.