MS SQL How to get the next month if its december - sql

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

Related

How to get last one month's data from a table based on current month and year?

I am facing some problem with the hive code.
My FROM TABLE is partitioned based on month, year and day. I came up with the following code to get the data I need. The logic is something like if the current mth is 01 then change the month to 12 and the year to yr - 1
else change month to mth - 1 and keep the year as is.
set hivevar:yr=2019;
set hivevar:mth=03;
set hivevar:dy=29;
SELECT * from
FROM table
WHERE
month = case when cast('${mth}' as int) = 01 then 12 else cast((cast('${mth}' as int) - 1) as string) end
AND year = case when cast('${mth}' as int) = 01 then cast((cast('${yr}' as int) - 1) as string) else '${yr}' end;
It is not working, my select * is coming empty. Please help.
desc table
From what i understand, you are trying to get data from the previous month given a date. If so, you can use inbuilt date functions to do it.
select *
from table
where concat_ws('-',year,month,day) >= add_months(date_add(concat_ws('-','${yr}','${mth}','${dy}'),1-'${dy}'), -1)
and concat_ws('-',year,month,day) < date_add(concat_ws('-','${yr}','${mth}','${dy}'),1-'${dy}')
The solution assumes year, month and day are of the format yyyy, MM and dd. If not, adjust them as needed
Also, you should consider storing date as a column even though you have it partitioned by year,month and day.

Adjusting dates and adding new rows

I am trying to calculate the difference between dates but in order to separate them out correctly by month I am hoping to add new rows instead of have a column for each month. I need the following:
If the month of a start date [ss_strt_dtd] equal the month of the end date [ss_end_dtd] then nothing needs to happen.
However, if the the months differ then I need the start date to remain the same but the end date to be the first date of the new month. Then a new start date in the first of the month and the end date to remain the same.
Example:
January 15, 2018 - January 18, 2018 - Nothing needs to happen
January 28, 2018 - February 2, 2018 would need to be split into two
rows that look like this:
[ss_strt_dtd]01/28/2018 [ss_end_dtd]02/01/2018
[ss_strt_dtd]02/01/2018 [ss_end_dtd]02/02/2018
Any thoughts would be appreciated!
You can use UNION:
select ss_strt_dtd, ss_end_dtd from [S&S_Combined]
where year(ss_strt_dtd) = year(ss_end_dtd) and month(ss_strt_dtd) = month(ss_end_dtd)
union all
select ss_strt_dtd, DateSerial(year(ss_end_dtd), month(ss_end_dtd), 1) from [S&S_Combined]
where year(ss_strt_dtd) <> year(ss_end_dtd) or month(ss_strt_dtd) <> month(ss_end_dtd)
UNION ALL select DateSerial(year(ss_end_dtd), month(ss_end_dtd), 1), ss_end_dtd from [S&S_Combined]
where year(ss_strt_dtd) <> year(ss_end_dtd) or month(ss_strt_dtd) <> month(ss_end_dtd);
You can this with a set of queries that also will work if the timespan covers many months.
First a small query to return 10 numbers:
SELECT DISTINCT Abs([id] Mod 10) AS N
FROM MSysObjects;
Save this as Ten.
Then a query to return a the series of months in your date interval:
PARAMETERS
[DateStart] DateTime,
[DateEnd] DateTime;
SELECT
[Ten_0].[N]+[Ten_1].[N]*10+[Ten_2].[N]*100+[Ten_3].[N]*1000+[Ten_4].[N]*10000+[Ten_5].[N]*100000+[Ten_6].[N]*1000000 AS Id,
[DateStart] AS DateStart,
[DateEnd] AS DateEnd,
DateAdd("m",[Ten_0].[N]+[Ten_1].[N]*10+[Ten_2].[N]*100+[Ten_3].[N]*1000+[Ten_4].[N]*10000+[Ten_5].[N]*100000+[Ten_6].[N]*1000000,[DateStart]) AS DateMonth
FROM
Ten AS Ten_0,
Ten AS Ten_1,
Ten AS Ten_2,
Ten AS Ten_3,
Ten AS Ten_4,
Ten AS Ten_5,
Ten AS Ten_6
WHERE
(((DateAdd("m",
[Ten_0].[N]+[Ten_1].[N]*10+[Ten_2].[N]*100+[Ten_3].[N]*1000+[Ten_4].[N]*10000+[Ten_5].[N]*100000+[Ten_6].[N]*1000000,
[DateStart]))<=DateAdd("m",
DateDiff("m", [DateStart],DateAdd("d",-1,[DateEnd])),[DateStart]))
AND ((Ten_0.N)<=DateDiff("m",[DateStart],[DateEnd])\1)
AND ((Ten_1.N)<=DateDiff("m",[DateStart],[DateEnd])\10)
AND ((Ten_2.N)<=DateDiff("m",[DateStart],[DateEnd])\100)
AND ((Ten_3.N)<=DateDiff("m",[DateStart],[DateEnd])\1000)
AND ((Ten_4.N)<=DateDiff("m",[DateStart],[DateEnd])\10000)
AND ((Ten_5.N)<=DateDiff("m",[DateStart],[DateEnd])\100000)
AND ((Ten_6.N)<=DateDiff("m",[DateStart],[DateEnd])\1000000));
Save this as MonthsDateRange.
Finally, calculate the From and To dates for each month respecting the start and end date:
SELECT
MonthsDateRange.Id,
MonthsDateRange.DateStart,
MonthsDateRange.DateEnd,
Year([DateMonth]) AS [Year],
Month([DateMonth]) AS [Month],
IIf(DateDiff("m",[DateStart],[DateMonth])=0,
[DateStart],
DateSerial(Year([DateMonth]),Month([DateMonth]),1)) AS DateFrom,
IIf(DateDiff("m",[DateEnd],[DateMonth])=0,
[DateEnd],
DateSerial(Year([DateMonth]),Month([DateMonth])+1,1)) AS DateTo,
DateDiff("d",[DateFrom],[DateTo]) AS Days
FROM
MonthsDateRange;
Save this as DaysMonthsDateRange.
It will return something like this:
Note, that the query is designed to be able to return the months of the entire range of data type Date.
That is 118800 records from 100-01-01 to 9999-12-31.

Get the month and year now then count the number of rows that are older then 12 months in SQL/Classic ASP

I know this one is pretty easy but I've always had a nightmare when it comes to comparing dates in SQL please can someone help me out with this, thanks.
I need to get the month and year of now then compare it to a date stored in a DB.
Time Format in the DB:
2015-08-17 11:10:14.000
I need to compare the month and year with now and if its > 12 months old I will increment a count. I just need the number of rows where this argument is true.
I assume you have a datetime field.
You can use the DATEDIFF function, which takes the kind of "crossed boundaries", the start date and the end date.
Your boundary is the month because you are only interested in year and month, not days, so you can use the month macro.
Your start time is the value stored in the table's row.
Your end time is now. You can get system time selecting SYSDATETIME function.
So, assuming your table is called mtable and the datetime object is stored in its date field, you simply have to query:
SELECT COUNT(*) FROM mtable where DATEDIFF(month, mtable.date, (SELECT SYSDATETIME())) > 12

Check whether date falls in the date range of the current year in sql

Suppose i have an input start date as "01/01/2014" and input end date as "31/01/2014". I need to check whether the input start date and input end date falls within highlighted record.In the highlighted record i have two columns monthfrom and monthto.Which is from December to February.But in my table there is no year mentioned.I need to take for current year but if i take current year then my query fails
SELECT * FROM tablename WHERE dateformatted BETWEEN '01/12/2014' AND '28/02/2014'
If i take end date as next year also again my query fails
SELECT * FROM tablename WHERE dateformatted BETWEEN '01/12/2014' AND '28/02/2015'.
Suppose i format the highlighted details as above query then i can check the input date falls within the date range.After checking the input date falls in the highlighted record i need to get number of days using weekfrom and weekto column.If i use this query
SELECT * FROM tablename WHERE dateformatted BETWEEN '01/12/2014' AND '28/02/2015'.
then will get wrong result because weekfrom will be different in the current year and next year.
Suppose i use the query like this
SELECT * FROM tablename WHERE dateformatted BETWEEN '01/12/2014' AND '28/02/2014'.Again i will not get the expected result because am checking for December to February of the current year.Please help me i need to check two conditions
Whether input date falls in the highlighted record
Count the number of days if it falls within the highlighted record with weekfrom and weekto keeping into consideration.
Week from and weekto may be in reverse order also as saturday to sunday(7 to 1).Here also we need to count the number of working days.
Instead of using this:
SELECT * FROM tablename WHERE dateformatted BETWEEN '01/12/2014' AND '28/02/2014'
Use this:
SELECT * FROM tablename WHERE dateformatted BETWEEN #01/12/2014# AND #28/02/2014#

return week number based on date

I am new to T-SQL and needed urgent assistance here.
I am trying to get the week number from a given date.
I understand that there is a build in function for it but the value return is not exactly what I wanted.
For e.g., by using select datepart(wk, '2013-01-07'), it would return me '2'.. but the actually fact is it should return '1' instead of '2'.
Any ideas how to correct this issue?
You can use dy datepart specifier to get dayOfYear number and divide it by 7:
select (datepart(dy, '2013-01-05') - 1) / 7 + 1;
Working DEMO.
Try this
SELECT DATEPART(WEEK,GETDATE())
This depends on hop you define the first week. Does it always start on the same weekday? or does it always start on the first of January? If you want it to always start on the same weekday, then use Set datefirst to tell T-SQL what weekdaty you want to define as the start of the week. If you want it to always start on Jan 1, then just use day of year instead of week, subtract 1, integer divide by 7 and add 1.
declare #dat DateTime = getdate()
Select Select (datepart(dy, #dat)-1) / 7 + 1
Although going from memory, I believe the ISO standard for the first week of the year is the week in the year that the first Thursday of the year is in. This would possibly explain why the built in function gives a result different to that you require.