SQL: how do you fetch a first day of the month? - sql

SQL: how do you fetch a first day of the month?
Hi,
I need to fetch a first day of every month from tbl.date from column start_date.
11/1/2017
12/1/2017
1/1/2018
2/1/2018
ETC.
Thanks

One solution in ANSI SQL looks like this:
select dte - (1 - extract(day from dte)) * interval '1 day'
In SQL Server, this would be:
select dateadd(day, 1 - day(dte), dte)
Similar functionality is available in almost any database.
If you just want the rows that are first days of the month, then:
where extract(day from dte) = 1
In SQL Server, this would be:
where day(dte) = 1
Of course, the syntax might be different depending on the database.

Another solution, using Postgres, in case you need to select the first row for each month, if there's no guarantee that that will be the first day of the month:
CREATE TABLE dates (
id BIGSERIAL PRIMARY KEY,
date TIMESTAMP NOT NULL
);
INSERT INTO dates(date)
VALUES ('2017-05-05'::timestamp), ('2017-05-02'::timestamp), ('2017-05-30'::timestamp), ('2017-05-25'::timestamp), ('2017-05-15'::timestamp), ('2017-05-01'::timestamp), ('2017-06-10'::timestamp), ('2017-06-02');
SELECT DISTINCT ON(EXTRACT(MONTH FROM date), EXTRACT(YEAR FROM date)) date
FROM dates
ORDER BY EXTRACT(MONTH FROM date), EXTRACT(YEAR FROM date), date ASC;
Results:
date
--------------------
2017-05-01T00:00:00Z
2017-06-02T00:00:00Z

Another solution, using Sql server
declare #FirstDOM date, #LastDOM datetime
set #FirstDOM = (select dateadd(d,-1,dateadd(mm,datediff(m,0,getdate()),1 )))
SELECT CONVERT( varchar, #FirstDOM,101);

Related

Oracle sql - get months id between two dates

I have date range eg. '2021-01-05' and '2021-02-10'. Two months January and February.
Need resaults:
Months
------
1
2
You want to iterate through the months. This is done with a recursive query in SQL:
with months (month_start_date) as
(
select trunc(:start_date, 'month') from mytable
union all
select month_start_date + interval '1' month
from months
where month_start_date < trunc(:end_date, 'month')
)
select
extract(year from month_start_date) as year,
extract(month from month_start_date) as month
from months
order by month_start_date;
You can use EXTRACT function that Oracle has to achieve this. In your case it should look something like:
SELECT EXTRACT (month FROM date_column) as "Months"
For more information about this function you can check out documentation here.

SQL Athena getting the data for the past 12 months

I need to grab the data for the past 12 months. I am using SQL within AWS Athena. Below is my code:
CREATE
OR REPLACE VIEW response_view AS
SELECT
"cust"."customer_id",
"cust"."event_triggered_date"
FROM
(
db.population_view pop
INNER JOIN new_db.manual_response_view cust ON ("pop"."customer_id" = "cust"."customer_id")
)
WHERE "cust"."event_triggered_date" > current_date - interval '12' month
Gives me an error: cannot be applied to varchar, date
event_triggered_filed is a string
This is the structure of the date field: 2019-12-04 00:00:00.000
Try this.
CAST(EVENT_TRIGGERED_DATE AS DATE)
OR
CAST(EVENT_TRIGGERED_DATE AS TIMESTAMP )
Data Types
I had same problem I need to get the stating day of the 6th and 12th month from current date.
I have written this, it works for me I hope it will work for other as well.
please refer attached image for query result
select current_date as today, date_add('month', -6, (select date(date_format(cast(current_date as date),'%Y-%m-01')))) as Start_of_the_date_6_month_before
For Staring day of the 12 month before date.
select current_date as today, date_add('month', -12, (select date(date_format(cast(current_date as date),'%Y-%m-01')))) as Starting_day_of_the_month_12_before
Finally i make this changes like this :
With
six_month_And_minus_1_day AS (
select date_add('month', -6, (select date(date_format(cast(current_date as date),'%Y-%m-01')))) as Start_of_the_date_6_month_before,
date_add('day', -1, date_add('month', -6, (select date(date_format(cast(current_date as date),'%Y-%m-01'))))) as Start_of_the_date_6_month_before_minus_1
)
select * from six_month_And_minus_1_day
Any one has better way to do this please suggest.

Get week number from a list of dates in SQL

I'm trying to get listed the corresponding week number from the dates that result from this query.
select Date,Time,EndDate,EndTime
FROM Test
WHERE (StartDate >= '01.01.2019')
ORDER BY StartDate
Basically, I want adding to the end column the week number from this query.
I can't edit the database in anyway, I just want to extract the week number from the dates and have it as a column at the end of my results.
Sample data below:
Just use datepart function:
select datepart(week, Date), Date,Time,EndDate,EndTime
FROM Test
WHERE (StartDate >= '01.01.2019')
ORDER BY StartDate
use datepart(wk,date):-
select Date,Time,EndDate,EndTime,datepart(wk,date)as week
FROM Test
WHERE (StartDate >= '01.01.2019')
ORDER BY StartDate
In UK ISO week is used: the first year's week is the one including 4th of Jan.
So:
set datefirst 1 --this sets Monday as first day of the week
set dateformat dmy -- nosrmal date format
select Date,Time,EndDate,EndTime,datepart(iso_week,date)as week
FROM Test
WHERE (StartDate >= '01.01.2019')
ORDER BY StartDate
Remember that first days of Jan may be 52nd or 53rd week of previous year and also last day of December may belong to first week of new year.
the check to see the week number and postponed to the yeear it belongs to is the following:
week_and_year = case when datepart(iso_week,date)>=52 and month(date)=1
then concat(year(date)-1,datepart(iso_week,date))
when datepart(iso_week,date)=1 and month(date)=12
then concat(year(date)+1,datepart(iso_week,date))
else concat(year(date),datepart(iso_week,date))
end
SELECT DATEPART(WEEK,GETDATE()-14)
SELECT DATEPART(WEEK,GETDATE()-7)
SELECT DATEPART(WEEK,GETDATE())
SELECT DATEPART(WEEK,GETDATE()+7)
SELECT DATEPART(WEEK,GETDATE()+14)
If you use Vertica, try this
date_part('ISODOW', date)
'ISODOW' - The ISO day of the week, an integer between 1 and 7 where Monday is 1.
I usually use the ROW_NUMBER() function to accomplish this:
select
Date,
Time,
EndDate,
EndTime,
ROW_NUMBER() over (partition by year(EndDate), datepart(weekday, EndDate) order by EndDate) as WeekNumInYear
FROM Test
WHERE
(StartDate >= '01.01.2019')
ORDER BY
StartDate

Know the week number of a month in bigquery

I want to know the week number of a month for a date in bigquery standard sql.In PostgreSQL if I write:
select To_char(current_date, 'YYYY-MM-W')<br>
It works for the date '25-04-2018' as 2018-04-4.
Here 2018 is the year, 04 is the month and 4 is the fourth week of the month in which the date falls.
I want something similar in bigquery standard sql.
If I write:
select format_date("%Y-%m",current_date())
It gives only 2018-04
I also want to know the week number of month.
Thank you in advance.
Here is solution (defining a UDF that you can use in a query) along with an example.
CREATE TEMP FUNCTION DateWithWeekOfMonth(date DATE) AS (
CONCAT(
FORMAT_DATE('%Y-%m-', date),
CAST(DIV(EXTRACT(DAY FROM date), 7) + 1 AS STRING)
)
);
SELECT date, DateWithWeekOfMonth(date)
FROM (
SELECT DATE '2018-04-01' AS date UNION ALL
SELECT DATE '2018-04-07' UNION ALL
SELECT DATE '2018-04-08' UNION ALL
SELECT DATE '2018-04-30'
);

Comparing dates in SQL Server

I have a DateTime column named EXP_Date which contains date like this :
2014-07-13 00:00:00.000
I want to compare them, like this query :
SELECT COUNT(*)
FROM DB
WHERE ('2014-07-15' - EXP_DATE) > 1
I expect to see the number of customers who have their services expired for over a month.
I know this query wouldn't give me the correct answer, the best way was if I separate the Year / Month / Day into three columns, but isn't any other way to compare them as they are?
You can use DATEADD
SELECT COUNT(*)
FROM DB
where EXP_DATE < DATEADD(month, -1, GETDATE())
Try this
SELECT COUNT(*)
FROM DB
where DATEADD(month, -1, GETDATE()) > EXP_DATE
SELECT COUNT(EXPIRE)FROM
(Select CASE WHEN EXP_DATE < DATEADD(month, -1, GETDATE())THEN 1 ELSE 0 END)AS EXPIRE FROM DB
)tt
Another way using DATEDIFF
SET DATEFORMAT DMY --I like to use "dateformat"
SELECT COUNT(*)
FROM DB
WHERE (DATEDIFF(DAY,#EXP_DATE,GETDATE())) >= 30 --Remember, instead "Day" you can use week, month, year, etc
Syntax: DATEDIFF ( datepart , startdate , enddate )
Depart: year, quarter, month, day, week...
For more information you can visit MSDN