Get previous month of a given date sql - sql

I had this:
select company
from alldata
where **{previous month of date("01.05.2011")}**
IN
(select month from alldata where SumNrSpot=0)
I need to find the previous month in the where clouse.
Please, anybody can help?

In case you're using MySQL:
SELECT MONTH(DATE_SUB('2011-05-01', 1 MONTH))
in your case
select company
from alldata
where MONTH(DATE_SUB('2011-05-01', 1 MONTH))
IN
(select month from alldata where SumNrSpot=0)
Read more about both functions here.

You may use DateAdd() method with parameter, month, and -1 as value to get previous month.
Following will give you
select DatePart(mm,DateAdd(m,-1,GetDate())) as PreviousMonth
For your query you can try:
select company
from alldata
where datepart(mm,dateadd(m,-1,Convert(DateTime, Convert(DateTime,'01.05.2011',104))))
IN (select month from alldata where SumNrSpot=0)

For SQL Server
You can just use the function MONTH() to get a month from a date.
You can use DATEADD(month,-1,) to adjust a date by a month.
You should always use the format YYYYMMDD if you present dates to SQL Server in textual form.
where MONTH(DATEADD(month,-1,'20110501') IN
That's assuming the table column alldata.month contains a numeric value of the month from 1-12.

extract month from given date and add -1
select ( extract (month from now()) -1 ) as previous_month

Select
DATEPART(mm,(DATEADD(m,-1,CONVERT(DATETIME,'01.05.2011')))) AS PreviousMonth
IN
(Select month from alldata where SumNrSpot=0)
Assuming your "Month" column is an integer value

I did it this way:
select company
from alldata
where MONTH(`Mon`) -1
IN
(select MONTH(Mon) from alldata where SumNrSpot=0)
Thanks anyway, some of your responses was useful and appreciated.

Related

SSIS Expression to get julian date from yesterday

Can anyone help me with SSIS Expression
I have this query in the expression:
Select period, * from table
I want to add a where clause to get period = yesterday
But, period column is in julian date format.
at the end i want the same result like this query
Select period, * from table
Where getdate() - 1
Thank you
you only can use you table date time column to compare with the getdate
Select period,
dataDate, *
from table
Where dataDate = getdate() - 1

SQL No of count month wise

I have a data set as below,
data is basically year and month YYYYMM, I need to bring a count of months eg 202001 is appearing 3 times, hence the count should be Nov 3 ( Desired output is shared below )
I'm unable to start to bring out the desired output, help would be much appreciated.
(Temp tables are not allowed to be created in the servers)
Please find the link for sample data link
Help would be much appretiated.
You can use to_date() to convert your number to a proper date, then group by that date:
select to_date(due_date_key::text, 'yyyymm') as due_date,
count(*)
from t
group by due_date;
The "due_date" column is a proper date, you can use the to_char() function to format it differently:
select to_char(due_date, 'yyyy') as year,
to_char(due_date, 'Mon') as output,
count
from (
select to_date(due_date_key::text, 'yyyymm') as due_date,
count(*)
from t
group by due_date
) t
order by due_date;
Online example

group by year month in postgresql

customer Date location
1 25Jan2018 texas
2 15Jan2018 texas
3 12Feb2018 Boston
4 19Mar2017 Boston.
I am trying to find out count of customers group by yearmon of Date column.Date column is of text data type
eg: In jan2018 ,the count is 2
I would do something like the following:
SELECT
date_part('year', formattedDate) as Year
,date_part('month', formattedDate) as Month
,count(*) as CustomerCountByYearMonth
FROM
(SELECT to_date(Date,'DDMonYYYY') as formattedDate from <table>) as tbl1
GROUP BY
date_part('year', formattedDate)
,date_part('month', formattedDate)
Any additional formatting for dates could be done on the inner query that will allow for adjustments in case some single digit days need to be padded or a month has four letters instead of three etc.
By converting to date type, you can properly order by date type and not alphabetical etc.
Optionally:
SELECT
Year
,Month
,count(*) as CustomerCountByYearMonth
FROM
(SELECT
date_part('year', to_date(Date,'DDMonYYYY')) as Year
,date_part('month', to_date(Date,'DDMonYYYY')) as Month
FROM <table>) as tbl1
GROUP BY
Year
,Month
You shouldn't store dates in a text column...
select substring(Date, length(Date)-6), count(*)
from tablename
group by substring(Date, length(Date)-6)
I thought #Jarlh asked a good question -- what about dates like January 1? Is it 01Jan2019 or 1Jan2019? If it can be either, perhaps a regex would work.
select
substring (date from '\d+(\D{3}\d{4})') as month,
count (distinct customer)
from t
group by month
The 'distinct customer' also presupposes you may have the same customer listed in the same month, but you only want to count it once. If that's not the case, just remove 'distinct.'
And, if you wanted the output in date format:
select
to_date (substring (date from '\d+(\D{3}\d{4})'), 'monyyyy') as month,
count (distinct customer)
from t
group by month
If it is a date column, you can truncate the date:
select date_trunc('month', date) as yyyymm, count(*)
from t
group by yyyymm
order by yyyymm;
I really read that the type was date. For a string, just use string functions:
select substr(date, 3, 7) as mmmyyyy, count(*)
from t
group by mmmyyyy;
Unfortunately, ordering doesn't work in this case. You should really be storing dates using the proper type.

SQL get records in the same week

I have a table that contains records with a column indicates the Date. Given a record, I would like to select all records that are in the same week as the record. How can SQL do that?
I should say that I'm using SQLite.
You can use DATEPART with wk to get the current week. Then just check for equality.
In this case, I have also checked yy to make sure that you do not check the year of a previous week.
SELECT *
FROM TABLE
WHERE DATEPART(wk, TABLE.DATECOLUMN)
= DATEPART(wk, (SELECT DATECOLUMN FROM TABLE WHERE ID = GivenID))
AND DATEPART(yy, TABLE.DATECOLUMN) = DATEPART(yy, (SELECT DATECOLUMN FROM TABLE WHERE ID = GivenID))
UPDATE FOR SQLITE
To do this in SQLLite, Refer to this SO question and then this article that states %W is what you use to get week and %Y for year. Which gives you:
SELECT *
FROM TABLE
WHERE STRFTIME('%W', TABLE.DATECOLUMN)
= STRFTIME('%W', (SELECT DATECOLUMN FROM TABLE WHERE ID = GivenID))
AND STRFTIME('%Y', TABLE.DATECOLUMN)
= STRFTIME('%Y', (SELECT DATECOLUMN FROM TABLE WHERE ID = GivenID))
Use the datediff() function:
datediff(ww,start_date,end_date) < 1
You can use BETWEEN to specify the records you want.
SELECT * FROM records WHERE datecolumn between 'YYYY/MM/DD' AND 'YYYY/MM/DD'

Return just the last day of each month with SQL

I have a table that contains multiple records for each day of the month, over a number of years. Can someone help me out in writing a query that will only return the last day of each month.
SQL Server (other DBMS will work the same or very similarly):
SELECT
*
FROM
YourTable
WHERE
DateField IN (
SELECT MAX(DateField)
FROM YourTable
GROUP BY MONTH(DateField), YEAR(DateField)
)
An index on DateField is helpful here.
PS: If your DateField contains time values, the above will give you the very last record of every month, not the last day's worth of records. In this case use a method to reduce a datetime to its date value before doing the comparison, for example this one.
The easiest way I could find to identify if a date field in the table is the end of the month, is simply adding one day and checking if that day is 1.
where DAY(DATEADD(day, 1, AsOfDate)) = 1
If you use that as your condition (assuming AsOfDate is the date field you are looking for), then it will only returns records where AsOfDate is the last day of the month.
Use the EOMONTH() function if it's available to you (E.g. SQL Server). It returns the last date in a month given a date.
select distinct
Date
from DateTable
Where Date = EOMONTH(Date)
Or, you can use some date math.
select distinct
Date
from DateTable
where Date = DATEADD(MONTH, DATEDIFF(MONTH, -1, Date)-1, -1)
In SQL Server, this is how I usually get to the last day of the month relative to an arbitrary point in time:
select dateadd(day,-day(dateadd(month,1,current_timestamp)) , dateadd(month,1,current_timestamp) )
In a nutshell:
From your reference point-in-time,
Add 1 month,
Then, from the resulting value, subtract its day-of-the-month in days.
Voila! You've the the last day of the month containing your reference point in time.
Getting the 1st day of the month is simpler:
select dateadd(day,-(day(current_timestamp)-1),current_timestamp)
From your reference point-in-time,
subtract (in days), 1 less than the current day-of-the-month component.
Stripping off/normalizing the extraneous time component is left as an exercise for the reader.
A simple way to get the last day of month is to get the first day of the next month and subtract 1.
This should work on Oracle DB
select distinct last_day(trunc(sysdate - rownum)) dt
from dual
connect by rownum < 430
order by 1
I did the following and it worked out great. I also wanted the Maximum Date for the Current Month. Here is what I my output is. Notice the last date for July which is 24th. I pulled it on 7/24/2017, hence the result
Year Month KPI_Date
2017 4 2017-04-28
2017 5 2017-05-31
2017 6 2017-06-30
2017 7 2017-07-24
SELECT B.Year ,
B.Month ,
MAX(DateField) KPI_Date
FROM Table A
INNER JOIN ( SELECT DISTINCT
YEAR(EOMONTH(DateField)) year ,
MONTH(EOMONTH(DateField)) month
FROM Table
) B ON YEAR(A.DateField) = B.year
AND MONTH(A.DateField) = B.Month
GROUP BY B.Year ,
B.Month
SELECT * FROM YourTableName WHERE anyfilter
AND "DATE" IN (SELECT MAX(NameofDATE_Column) FROM YourTableName WHERE
anyfilter GROUP BY
TO_CHAR(NameofDATE_Column,'MONTH'),TO_CHAR(NameofDATE_Column,'YYYY'));
Note: this answer does apply for Oracle DB
Here's how I just solved this. day_date is the date field, calendar is the table that holds the dates.
SELECT cast(datepart(year, day_date) AS VARCHAR)
+ '-'
+ cast(datepart(month, day_date) AS VARCHAR)
+ '-'
+ cast(max(DATEPART(day, day_date)) AS VARCHAR) 'DATE'
FROM calendar
GROUP BY datepart(year, day_date)
,datepart(month, day_date)
ORDER BY 1