How to easily get year and month with leading zero in BigQuery? - sql

I have a snapshot date in the following format: 2021-06-28 and I would like to have it like that: 202106. So the first four digits is year and next two is the month with leading zero. I tried this code:
concat(extract(year from snapshot_date), extract(month from snapshot_date))
but I have in return: 20216, without leading zero. How can I easily get it without CASE statement?

Try format_date:
select format_date("%Y%m", snapshot_date)
from mytable

Assuming snapshot_date is of date data type - you can use recently introduced Format clause for CAST as in below example
select cast(snapshot_date as string format 'YYYYMM')
from `project.dataset.table`

if "snapshot_date" is in date format, then this should work
select to_char(snapshot_date, 'yyyymm') from table_name

As a note, you can return the value as a number and just use multiplication:
(extract(year from snapshot_date) * 100 + extract(month from snapshot_date)) as yyyymm

Related

Converting date format number to date and taking difference in SQL

I have a data set as below,
Same is date in "YYYYMMDD" format, I wanted to convert the columns to date format and take the difference between the same.
I used to below code
SELECT to_date(statement_date_key::text, 'yyyymmdd') AS statement_date,
to_date(paid_date_key::text, 'yyyymmdd') AS paid_date,
statement_date - paid_date AS Diff_in_days
FROM Table
WHERE Diff_in_days >= 90
;
Idea is to convert both the columns to dates, take the difference between them and filter cases where difference in days is more than 90.
Later I was informed that server is supported by HiveSQL and does not support of using ":", date time, and temp tables can not be created.
I'm currently stuck on how to go about given the constraints.
Help would be much appreciated.
Sample date for reference is provided in the link
dbfiddle
Hive is a little convoluted in its use of dates. You can use unix_timestamp() and work from there:
SELECT datediff(to_date(unix_timestamp(cast(statement_date_key as varchar(10)), 'yyyyMMdd')),
to_date(unix_timestamp(cast(paid_date_key as varchar(10)), 'yyyyMMdd'))
) as diff_in_days
FROM Table;
Note that you need to use a subquery if you want to use diff_in_days in a where clause.
Also, if you have date keys, then presumably you also have a calendar table, which should make this much simpler.
Hello You Can Use Below Query It Work Well
select * from (
select convert(date, statement_date_key) AS statement_date,
convert(date, paid_date) AS paid_date,
datediff(D, convert(date, statement_date_key), convert(date, paid_date)) as Diff_in_days
from Table
) qry
where Diff_in_days >= 90
Simple way: Function unix_timestamp(string, pattern) converts string in given format to seconds passed from unix epoch, calculate difference in seconds then divide by (60*60*24) to get difference in days.
select * from
(
select t.*,
(unix_timestamp(string(paid_date_key), 'yyyyMMdd') -
unix_timestamp(string(statement_date_key), 'yyyyMMdd'))/86400 as Diff_in_days
from Table t
) t
where Diff_in_days>=90
You may want to add abs() if the difference can be negative.
One more method using regexp_replace:
select * from
(
select t.*,
datediff(date(regexp_replace(string(paid_date_key), '(\\d{4})(\\d{2})(\\d{2})','$1-$2-$3')),
date(regexp_replace(string(statement_date_key), '(\\d{4})(\\d{2})(\\d{2})','$1-$2-$3'))) as Diff_in_days
from Table t
) t
where Diff_in_days>=90

Postgres: How do I extract year and month from a date?

One of my columns is a date type in the following format: YYYY-MM-DD. I want to extract YYYY-MM. So far, the resources I've come across show me that I can extract either year using SELECT extract(year from order_date)... but I can't figure out how to extract both the year and the month. I tried the following but it didn't work: https://www.w3schools.com/sql/func_mysql_extract.asp
I just want to point out that it is often convenient to leave the value as a date. If so, use date_trunc():
select date_trunc('month', order_date) as yyyymm
If you really want a string, you should accept Nick's answer.
In PostgreSQL you can use TO_CHAR():
SELECT TO_CHAR(order_date, 'YYYY-MM')
Output (if order_date = '2020-04-06'):
2020-04
Note if your column is not already a date or timestamp you will need to cast it to a date or timestamp (e.g. order_date::date).
Demo on dbfiddle

oracle compare a date with the current date

I have to convert a column to a date and then compare the month of the column with the current month.
The column looks like this :
Date
0117
0217
0317
..
I know how to convert it but cant compare it.
select date,to_date(date, 'mmyy')
from table
where ????
any ideas?
You can convert the value to a date using to_date():
select to_date(mmyy, 'MMYY')
from t;
Note that I renamed the column mmyy to clarify what it contains.
This returns the first day of the month.
The result of to_date() can then be compared to the current date. For instance, to match the first of date of the month:
where to_date(mmyy, 'MMYY') = trunc(sysdate)
If you want to match everything in the month, just use an appropriate comparison:
where to_char(to_date(mmyy, 'MMYY'), 'YYYY-MM') = to_char(sysdate, 'YYYY-MM')
or, more simply:
where mmyy = to_char(sysdate, 'MMYY')
You can convert the current date to a string and use string comparisons (which would allow you to use an index on your column):
SELECT *
FROM your_table
WHERE your_date_column = TO_CHAR( SYSDATE, 'MMYY' )
or you can convert the column to a date and compare it (which would not use an index on your column but could use a function-based index, if you created one):
SELECT *
FROM your_table
WHERE TO_DATE( your_date_column, 'MMYY' ) = TRUNC( SYSDATE, 'MM' )

Extract month and year from date in oracle

what is the query for extract month and year from full date.
my data is like this: 1/29/2008
I tried this query:
select ID_NO, CHECKED_DATE, to_date(TO_CHAR(CHECKED_DATE, 'MON-YYYY'), 'MON-YYYY') AS A
from Doctor_Checkup;
but It will give output: 1/1/2008
Expected output: 1-2008
If the field is already a date column, you can simply cast it to the format you want:
select ID_NO,CHECKED_DATE,ltrim(TO_CHAR(CHECKED_DATE,'mm-yyyy'),'0') AS A from Doctor_Checkup;
If it is a text column, you will need to cast to a date with format first:
select ID_NO,CHECKED_DATE,ltrim(TO_CHAR(TO_DATE(CHECKED_DATE,'dd/mm/yyyy'),'mm-yyyy'),'0') AS A from Doctor_Checkup;
A date does not have a format - it is stored internally to the database as 7-bytes (representing year, month, day, hour, minute and second) and it is not until whatever user interface you are using (i.e. SQL/Plus, SQL Developer, Java, etc) tries to display it to you, the user, and converts it into something you would find meaningful (usually a string) that the date has a format.
One thing to note is that a date always has the year, month, day, hour, minute and second components. Doing:
to_date(TO_CHAR(CHECKED_DATE, 'MON-YYYY'), 'MON-YYYY')
Is effectively the same as doing:
TRUNC( Checked_Date, 'MM' )
and will still have a day, hour, minute and second component but will have been truncated to midnight of the first day of the month. The user interface may just be have its preferences set to not display the time component (but the date will still have one).
What you want to do is convert the date to a formatted string:
select ID_NO,
CHECKED_DATE,
TRIM( LEADING '0' FROM TO_CHAR( CHECKED_DATE, 'MM-YYYY') ) AS A
from Doctor_Checkup;
or
select ID_NO,
CHECKED_DATE,
EXTRACT( MONTH FROM CHECKED_DATE )
|| '-' || EXTRACT( YEAR FROM CHECKED_DATE ) AS A
from Doctor_Checkup;
You want a string representing month and year in the format [M]M-YYYY. Oracle's TO_CHAR only supports MM-YYYY, though, so you'd have to get rid of a leading zero if any.
Two solutions:
trim(leading '0' from to_char(checked_date, 'mm-yyyy'))
or
extract(month from checked_date) || '-' || extract(year from checked_date) from dual
To get 1-2008 format use the following format with trimming leading zeroes:
select ID_NO,CHECKED_DATE,ltrim(TO_CHAR(CHECKED_DATE,'MM-YYYY'),'0') AS A from Doctor_Checkup;
SELECT ID_NO, CHECKED_DATE FROM DOCTOR_CHECKUP EXTRACT(MONTH FROM CHECKED_DATE) IN (6) AND EXTRACT(YEAR FROM CHECKED_DATE) IN (2019);
6 MEANS THE MONTH AND 2019 IS THE YEAR
LTRIM(TO_CHAR(TO_DATE(<date_field>,'YYYYMMDD'),'YYYY-MM'),'09'))

YYYYMMDD to YYYYMM in oracle

I have a column with DATE datatype in a table.
I am trying to retrieve the column values in YYYYMM format. My select query looks like below
select *
from tablename
where date column = to_char(to_date('12/31/4000','MM/DD/YYYY'),'YYYYMM');
I am getting below exception.
ORA-01847: day of month must be between 1 and last day of month
Appreciate any input on this.
I think the simplest method is:
where to_char(datecolumn, 'YYYYMM') = '400012'
Or, if you prefer:
where to_char(datecolumn, 'YYYYMM') = to_char(to_date('12/31/4000', 'MM/DD/YYYY'), 'YYYYMM');
Syntax-wise, the right hand date (to the right of the equals) is OK. But you are doing a character comparison, not a date comparison.
This works for me in multiple databases:
select to_char (to_date('12/31/4000','MM/DD/YYYY'),'YYYYMM')
from dual;
Even though your column is named DATE_COLUMN, you are comparing based on characters in the query.
So, try this instead - this compares based on dates (NOT a character comparison) and truncates off the hour, minute, ETC. so you are only comparing the DAY:
select * from DATE_TAB
where TRUNC(DATE1, 'DDD') = TRUNC(to_date('12/31/4000','MM/DD/YYYY'),'DDD');
NOTE: The DATE1 field above is a DATE field. If you're DATE_COLUMN is not a DATE field, you must
convert it to a DATE datatype first (using TO_DATE, ETC.)
Assuming that "date_column" is actually a date, and that you have an index on date_column, you can do something like this to return the data quickly (without truncating dates in all rows to do a comparison):
with dat as (
select level as id, sysdate - (level*10) as date_column
from dual
connect by level <= 100
)
select id, date_column
from dat
where date_column between to_date('11/1/2013', 'MM/DD/YYYY') and last_day(to_date('11/2013 23:59:59', 'MM/YYYY HH24:MI:SS'))
Here I just dummy up some data with dates going back a few years. This example picks all rows that have a date in the month of November 2013.
If your date_column's data-type is DATE, then use
select *
from tablename
where TO_CHAR(date_column,'YYYYMM') = to_char (to_date('12/31/4000','MM/DD/YYYY'),'YYYYMM');
If your date_column's data-type is VARCHAR, then use:
select *
from tablename
where date_column = to_char (to_date('12/31/4000','MM/DD/YYYY'),'YYYYMM');
I somehow feel your error is because you have a space between date and column as
"date column". If the field name in the table is "COLUMN", then just removing the word "DATE" from your original query would suffice, as:
select *
from tablename
where column = to_char(to_date('12/31/4000','MM/DD/YYYY'),'YYYYMM');
If your column (YYYYMMDD) is in number format, the simplest way to get YYYYMM would be
select floor(DATE/100)
from tablename;