Plus 2 date in SQL - sql

I really need help on this those function DATEDIFF OR DateAdd , because I have no idea on those things.
Declare #EstDate as Date,
#Shipdate as Date,
#Workingday as Int,
I need to do like this:
#EstDate(Date) = #ShipDate(DATE) - #WorkingDay(int) - 2days
Example: #EstDate(date) = '6/11/2011' - 5days - 2days.
How can I do this formula in SQL ? >_< In PHP its easy, but in SQL 2000 up, I have no ideas.

I think this will do it. Basically this adds a negative number of days to #ShipDate. The negative number of days will equal #WorkingDay + 2.
I really don't know what #WorkingDay is supposed to represent. This example assumes it's just a number that represents something to you.
#EstDate = DateAdd(dd,-(#WorkingDay + 2),#ShipDate)
It would look something like this, given your example:
#EstDate(date) = DateAdd(dd, -(5 days + 2 days), '6/11/2011')

Related

Multiply by number of days in a month

I've had a decent search on here but can't seem to find what I'm looking for, I think I'm using an incorrect syntax for GETDATE
I'm trying to use a formula that we use as a company to work within my code. That is;
The Price of something / Days in year * days in the month
I'm trying to use the following but to no avail -
[Rate] = Price/'365'*month([Period])))
'Period' is the column name which has the date of the month in the format '2018-04-01' for example
This is based on an example a colleague has shown me but I can't get it to work as I think I'm writing it totally wrong
Apologies for the simple question, I'm brand new to SQL code (well only started in April) so some simple things till are oblivious to me!
Any help here would be really appreciated
Cheers
W
I think you want something like this (assuming 365 days in a year):
select (price / 365.0) * day(eomonth(period)) as rate
If you want to take leap years into account, then:
select (case when eomonth(day(year(period)), 2, 1)) = 28
then (price / 365.0) * day(eomonth(period))
else (price / 366.0) * day(eomonth(period))
end) as rate
I think your code will be like below
[Rate] = (Price*1.00/365) * datepart(day, period)
below is an example by using getdate()
select rate= (12*1.00/365) * datepart(day, getdate())

Datediff function in hive

Regarding DateDiff function
select datediff(current_date, '-2018-01-21');
what is - here as I know datediff(enddata,startdate)
if we mention minus for startdate it getting number values 1474138
can please help to understand
Below query confirms that a negative date is similar to a negative integer. If you subtract a negative number to a positive number, it is the same as adding their absolute values (ignoring the signs). For example; 8 - (-4) = 8 + 4
Thus, since the minimum date value for date type is '0000-01-01', we measure the number of days from year -2018 to 0000 and add to the number of days from 0000 to 2018. Then, we get 1474137 ( = 737122 + 737015). Hope this helps. Thanks.
Query:
select datediff('2018-03-02', '0000-01-01'), datediff('0000-01-01', '-2018-03-01'), datediff('2018-03-02', '-2018-03-01')
Result:
737122 737015 1474137
Again, 737122 + 737015 = 1474137. There are 1474137 days since 2018-Mar-01 BC.

Converting a time excel formula to t-sql

So I'm new to SQL (I believe it's T-SQL) and I'm trying to convert a function I used in Excel to SQL.
L2 becomes Column 1
G2 becomes Column 2
=(INT(L2)-INT(G2))*("17:00"-"08:45")+MEDIAN(MOD(L2,1),"17:00","08:45")-MEDIAN(MOD(G2,1),"17:00","08:45")
What this does is calculate the business hours worked between 8:45AM and 05:00PM.
If work goes from 4:00PM to 9:00AM the next day, the result should be 01:15:00.
If it goes over several days (4:00PM on the 1st to 9:00AM on the 4th) it should be 17:45:00.
I'd prefer not to have a separate function because I don't know how to use them as I'm quite new to this - I'd prefer to have it as something I can write within the SELECT * , <code here here> FROM db.name section.
Thanks in advance
I know you said you don't want this in a function, but they really aren't hard to use and the logic you require for this is too complex in SQL Server to be sensibly contained inline (Though it can be, if you really want to be that guy).
This function has no error handling if any of your parameters are not suitable, though I will leave that up to you as a learning exercise on NULL values, process flows and fully thinking through all the possibilities that you may need to deal with:
-- This bit creates your function. You can rename the function from fnWorkingDays to anything you want, though try to keep your naming conventions sensible:
create function fnWorkingDays(#Start datetime
,#End datetime
)
returns decimal(10,2)
as
begin
-- Declare the start and end times of your working day:
declare #WorkingStart time = '08:45:00.000'
declare #WorkingEnd time = '17:00:00.000'
-- Work out the number of minutes outside the working day in 24 Hour Notation:
declare #OvernightMinutes int = datediff(minute -- Work out the difference in minutes,
,cast(#workingend as datetime) -- between the end of the working day (CASTing a TIME as DATETIME gives you 1900-01-01 17:00:00)
,dateadd(d,1,cast(#WorkingStart as datetime)) -- and the start of the next working day (CAST the TIME value as DATETIME [1900-01-01 08:45:00] and then add a day to it [1900-01-02 08:45:00])
)
-- There is no need to retain the minutes that fall outside your Working Day, to if the very start or very end of your given period fall outside your Working Day, discard those minutes:
declare #TrueStart datetime = (select case when cast(#Start as time) < #WorkingStart
then dateadd(d,datediff(d,0,#Start),0) + cast(#WorkingStart as datetime)
else #Start
end
)
declare #TrueEnd datetime = (select case when cast(#End as time) > #WorkingEnd
then dateadd(d,datediff(d,0,#End),0) + cast(#WorkingEnd as datetime)
else #End
end
)
-- You can now calculate the number of minutes in your true working period, and then subtract the total overnight periods in minutes to get your final value.
-- So firstly, if your Working Period is not long enough to stretch over two days, there is not need to do any more than calculate the difference between the True Start and End:
return (select case when datediff(minute,#Start,#End) < #OvernightMinutes
then datediff(minute,#TrueStart,#TrueEnd)
-- If you do need to calculate over more than one day, calculate the total minutes between your True Start and End, then subtract the number of Overnight Minutes multiplied by the number of nights.
-- This works because DATEDIFF calculated the number of boundaries crossed, so when using DAYS, it actually counts the number of midnights between your two dates:
else (datediff(minute,#TrueStart,#TrueEnd) - (datediff(d,#TrueStart,#TrueEnd) * #OvernightMinutes))/1440.
-- If you want to return your value in a slightly different format, you could use variations of these two, though you will need to change the RETURNS DECIMAL(10,2) at the top to RETURNS NVARCHAR(25) if you use the last one:
-- else datediff(minute,#TrueStart,#TrueEnd) - (datediff(d,#TrueStart,#TrueEnd) * #OvernightMinutes)
-- else cast((datediff(minute,#TrueStart,#TrueEnd) - (datediff(d,#TrueStart,#TrueEnd) * #OvernightMinutes))/60 as nvarchar(5)) + ' Hours ' + cast((datediff(minute,#TrueStart,#TrueEnd) - (datediff(d,#TrueStart,#TrueEnd) * #OvernightMinutes))%60 as nvarchar(5)) + ' Minutes'
end
)
end
go
And this is how you call the function:
select dbo.fnWorkingDays('2016-09-04 12:00:00.000', '2016-09-06 12:10:00.000') as WorkingDays
You can replace the two DATETIME values about with the appropriate column names to get your desired result inline:
select dbo.fnWorkingDays(Dates.StartDate, Dates.EndDate) as WorkingDays
from (select '2016-09-04 12:00:00.000' as StartDate
,'2016-09-06 12:10:00.000' as EndDate
) as Dates

How to show rows where date is equal to every 7 days from a specific day

I'd like to show every row where date_added equals '2015-02-18' and every seven days after, so '2015-02-25' and '2015-03-04' etc..
here's what I have so far
select * from table
where ((to_char(date_added, 'j')) /
((select to_char(d,'j') from (select date '2015-02-18' d from dual)))) = 1
That gets me the first desired date, however I'm stuck as to how to express it to show the next 7 days as a step additive function.
Any help is appreciated. Thank you.
One way to do this is with mod():
select *
from table
where mod(date_added - date '2015-02-18', 7) = 0;
Note: this assumes that the dates have no time component. If they do, then use trunc() to get rid of it.
I like Gordon's "mod()" solution but he's missing part of the requested solution.
In this case, I have a "calendar" table that includes a series of dates:
http://www.perpendulum.com/2012/06/calendar-table-script-for-oracle/
select *
from calendar
where date_time_start >= to_date('01-Jan-2013')
and mod(trunc(date_time_start) - to_date('01-Jan-2013'), 7) = 0;
Per the original question, you want records where the dates are equal to a given date and every seven days thereafter.

SQL figuring out days remaining based on days interval (using SQL Server 2005)?

I have a table that represents a user's subscription to our system. I have two tables. One represents the subscription for an account and the other represents the type of subscription. The subscription table relates to the subscription type table with a subscriptionTypeID field in the subscription types table. I need to figure out the days remaining for that account. Here is my example:
The user signed up on January 1, 2010 and their term is 30 days. Based on today's date (January 25, 2010) they would have 6 days remaining.
I need help designing the SQL. Here is what I have so far in my stored procedure:
#SubscriptionTypesID int
Declare #term int
Declare remainder int
Set #term = (SELECT subscriptionTerm
FROM dbo.SubscriptionTypes
where dbo.SubscriptionTypes.SubscriptionTypesID = #SubscriptionTypesID)
Now i need to figure out what to do with the remainder query, or if I can somehow have one SQL statement so I don't have to get the term separately.
Update:
Here is what I got now with all your help, but I still want a more elgant way to pump the term field value into the query:
Select (DateDiff(day,getDate(),DATEADD (day , 30, '01/01/2010' ))) days
Update 2.0 ;)
Sometimes the answer is right in front of me and I can't even see it. I tend to over think problems and make them more complicated than they need to be. Thanks to everyone who helped! HEre is the code:
SELECT (DateDiff(day,getDate(),DATEADD (day , subscriptionTerm, dbo.Subscriptions.subscriptionDate ))) days
FROM
dbo.Subscriptions
INNER JOIN dbo.SubscriptionTypes ON (dbo.Subscriptions.subscriptionTypeID = dbo.SubscriptionTypes.SubscriptionTypesID)
WHERE
dbo.Subscriptions.userID = 129
You can use Datadiff functionality from sql:
http://msdn.microsoft.com/en-us/library/ms189794.aspx
You could also solve it using:
DATEADD (datepart , number, date )
You can find more in the same MSDN page, just use the searchbox and type "Dateadd"
Good luck with your remaining time thingie ;)
Err, why don't you just compare the current date to the subscription date +30 days? I believe that would look like
if(GETDATE() > DATEADD(day,30,#SubscriptionDate))
BEGIN
END
In the comments below you asked how to get teh number of days. SQL has a method for that...
SELECT DATEDIFF(datepart,start,end)
To get the value and use it in different places you can use the following syntax:
DECLARE #Difference int
SELECT #Difference = DATEDIFF(day,#SubscriptionDate,GETDATE())
HEre it is...Thanks all for the insight:
SELECT (DateDiff(day,getDate(),DATEADD (day , subscriptionTerm, dbo.Subscriptions.subscriptionDate ))) days
FROM
dbo.Subscriptions
INNER JOIN dbo.SubscriptionTypes ON (dbo.Subscriptions.subscriptionTypeID = dbo.SubscriptionTypes.SubscriptionTypesID)
WHERE
dbo.Subscriptions.userID = 129