I need to convert the following Function of SQL Server To MySQL. I am new to MySQL. Help needed.
the Function returns a generated Id based on the date :
-S1 or S2 ..S5 : the letter S followed by the number of week on month start from monday
-0X the month in two digits
-15 the year in two digits
Ex :
2015/06/01 to 2015/06/07 is S10615
2015/06/29 to 2015/07/05 is S50615
2015/07/06 to 2015/07/12 is S10715
Function
Create Function GetIdPanier()
Returns Varchar(25)
As
Begin
declare #week varchar(2) = DATEPART(DAY, DATEDIFF(DAY, 0, GETDATE())/7 * 7)/7 + 1
declare #month int = case when DATEPART(DAY,GETDATE()) < 7 and #week > 1
then DATEPART(MONTH,DATEADD(MONTH,-1,GETDATE()))
else DATEPART(MONTH,GETDATE())
end
return 'S' + #week + RIGHT('00' + CAST(#month AS varchar(2)), 2) + RIGHT(CAST(DATEPART(yyyy, GETDATE()) AS varchar(4)), 2)
End
MYSQL have function EXTRACT (like DatePart in MS SQL).
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_extract
Related
Any help with the syntax would be appreciated.
Datediff(day,dateOne, dateTwo) as TimeServed
How would I get the number of days between those dates excluding Saturday and Sunday?
I do not have the ability to create functions.
Please check out below code, it might help:
declare #firstdate Date
declare #seconddate Date
set #firstDate = convert(date, '2019-11-01')
set #seconddate = convert(date, '2019-11-30')
select ((datediff(dd, #firstDate, #secondDate)+1) -
( DateDiff(wk, #firstDate, #secondDate) * 2) -
case when datepart(dw, #FirstDate) = 1 then 1 else 0 end -
case when datepart(dw, #secondDate) = 7 then 1 else 0 end)
I'm trying to convert a Hundred Year Date (HYD) format to a regular date format through SSIS derived column transform. For example: Convert 41429
to 06/04/2013. I can do it with formatinng code within a script (and maybe I simply have to go this route) but feel there has to be a way to do so within a derived column that I'm just not getting. Any help is appreciated.
This is what I came up with. Are you sure your conversion is correct? My answer is 1 day. off.
DECLARE #t1 as date = '01/01/1900';
DECLARE #t2 as DATE = '12/31/1900';
DECLARE #hyd as INT;
-- This example shows that we need to add 1
SELECT #hyd = DATEDIFF (d, #t1, #t2) + 1 -- 364 + 1
SELECT #hyd
set #t2 = '06/04/2013';
SELECT #hyd = DATEDIFF (d,#t1, '06/04/2013') + 1-- 41427
SELECT #hyd
SELECT DATEADD (d, #hyd, '01-JAN-1900')
SELECT DATEADD (d, 41429, '01-JAN-1900')
A hundred year date is a calculation based on the number of days since 1899-12-31. It's an "Excel Thing". It also has a bug in it that you must account for.
The equivalent TSQL logic would be
DECLARE
#HYD int = 41429;
SELECT
#HYD =
CASE
WHEN #HYD > 60
THEN #HYD -1
ELSE
#HYD
END;
SELECT
DATEADD(d, #HYD, '1899-12-31') AS HYD;
Armed with that formula, I can write the following Expression in a Derived Column Transformation (assuming you have a column named HYD)
(HYD > 60) ? DATEADD("d",HYD - 1,(DT_DATE)"1899-12-31") : DATEADD("d",HYD,(DT_DATE)"1899-12-31")
And the results
--or inline SQL...using this
SELECT
case when ([HYD] > 60) then
DATEADD(day,[HYD] - 1,'1899-12-31')
else
DATEADD(day,[HYD],'1899-12-31')
end 'HYD_conv'
FROM
TableName
--and in the where clause if you like...
WHERE
(case when ([HYD] > 60) then DATEADD(day,[HYD] - 1,'1899-12-31') else DATEADD(day,[HYD],'1899-12-31') end) = '2016-01-14'
How to get the financial day of the year i.e., if i pass 2nd of april to the function, it should return 2. The financial year starts on 1st of April for every year.
Fiscal calendars are specific to the organization and, although rare, can change. The simplest solution is to create a table that outlines the Fiscal calendar. So, you can mimic this using a CTE but it is better to store it as a table.
With FiscalCalendarStarts As
(
Select 1 As FiscalPeriod
, Cast('20120401' As DateTime) As StartDate
Union All
Select FiscalPeriod + 1
, Case
When Month(StartDate) = 12 Then DateAdd(m, Month(StartDate) - 12 + 1, StartDate)
Else DateAdd(m, 1, StartDate)
End
From FiscalCalendarStarts
Where FiscalPeriod < 12
)
, FiscalCalendar As
(
Select FiscalPeriod
, StartDate
, DateAdd(d, -1, DateAdd(m, 1, StartDate)) As EndDate
From FiscalCalendarStarts
)
Select *
From FiscalCalendar
Where #SomeDate Between StartDate And EndDate
Edit
To get the day count (which I admit I did not provide in the above solution), the trick is to determine the actual fiscal year start date based on the input date. To do that, you could do something like the following, which per your request, I've put into a function
Create Function dbo.FiscalDay ( #Input datetime )
Returns int
As
Begin
Declare #StartDayMonth char(4);
Set #StartDayMonth = '0401';
Return (
Select DateDiff(d, FYStartDate, #Input) + 1
From (
Select DateAdd(yyyy
, Case
When DatePart(dy, #Input) >= DatePart(dy, StartDate) Then 0
Else -1
End
, StartDate) As FYStartDate
From (
Select Cast( Cast(Year(#Input) As char(4))
+ #StartDayMonth As datetime ) As StartDate
) As S1
) As S
)
End
I start with the stub of 0401 which represents the month and day of the start of the fiscal year. To that I prepend the passed date's year so I get something like 20120401 if a date in 2012 was passed. If #Input is later than 1-Apr, then we're in the new fiscal year for the year of the #Input. If #Input is earlier than 1-Apr, then we're in the fiscal year that start on 1-Apr of the previous year. Now that we have the fiscal start date, we can simply find the numbers of days between them and add 1 (otherwise 1-Apr will be seen as day 0 instead of day 1). Note that passing 31-Mar-2012 returns 366 instead of 365 since 2012 was a leap year.
#Olivarsham, The financial year in not common for every country. Some where it is Apr-mar, some where it is Jan-Dec. So It it is your special application requirement then you need to write for your self. I think no standard query for that.
Kindly try this function. This will return your the day number of the fiscal year.
CREATE FUNCTION [dbo].[FiscalDay] (#CurrentDATE datetime)
RETURNS int
AS
BEGIN
DECLARE #FiscalDay int;
DECLARE #YearStartDate DateTime;
Set #YearStartDate=Cast('20120401' As DateTime)
set #FiscalDay = DATEDIFF(DAY,#YearStartDate , #CurrentDATE)
RETURN(#FiscalDay);
END;
GO
I have this code which I'm writing into a stored procedure:
declare #StartTime time
declare #EndTime time
declare #Temp_StartTime time
declare #temp_StartHour int
declare #temp_EndHour int
declare #temp_StartMinute int
declare #temp_EndMinute int
SET #StartTime='22:30:00'
SET #EndTime='00:52:00'
SET #Temp_StartTime=#StartTime
SET #temp_StartHour=DATEPART(HOUR, #StartTime)
SET #temp_EndHour=DATEPART(HOUR, #EndTime)
SET #temp_StartMinute=DATEPART(MI, #StartTime)
SET #temp_EndMinute=DATEPART(MI, #EndTime)
if(#temp_EndMinute>0)
BEGIN
SET #temp_EndHour=#temp_EndHour+1
END
DECLARE #Temp_Table TABLE
(
StartHour int,
StartMinute int,
EndHour int,
EndMinute int,
StartTime time,
EndTime time
)
WHile((#temp_EndHour-#temp_StartHour>=1))
BEGIN
INSERT INTO #Temp_Table
SELECT (DATEPART(HOUR, #Temp_StartTime)) AS StartHour,(DATEPART(MINUTE, #Temp_StartTime)) AS StartMinute,
#temp_StartHour+1 AS EndHour,
0 AS EndMinute, #StartTime as StartTime, #EndTime as EndTime
SET #temp_StartHour=#temp_StartHour+1
SET #Temp_StartTime=DATEADD(HOUR,1,#Temp_StartTime)
if(DATEPART(MI, #Temp_StartTime)!=0)
BEGIN
SET #Temp_StartTime=DATEADD(MI,-#temp_StartMinute,#Temp_StartTime)
END
END
SELECT * FROM #Temp_Table
It works great if you use any time value other than the 00:52:00 example I have up there. For instance, if EndTime was 23:05, the stored procedure works great. I did some research around DATEPART but didn't find anything helpful as to how to get it to calculate midnight at military time properly.
EDIT: When the code runs properly, it calculates the time in how many hours between start and end time and the idea is to store new rows for each hour into the temp table (eventually this is going to be saved to a new table for tracking outages by hour). It works find when I run it with 21:30 to 22:15. I get two rows reflecting 21:00 to 22:00 and 22:00 to 23:00 (this is the logic I want). But throw military midnight in there, and I get no rows returned as the calc won't compute the 00.
I have found examples in my database that show start times of 22:00:0000 and end times of 00:00:00.0000000 and then visa versa. So one way WILL calculate, where start time is 00, but if start time is 21:00:0000 and end time is 00:52:0000 then no dice. I get no rows returned.
If I am not missing anything, this is what you could try instead of your loop:
DECLARE
#StartTime time,
#EndTime time;
SET #StartTime = '22:30:00';
SET #EndTime = '00:52:00';
WITH timerange AS (
SELECT
StartTime = CAST(#StartTime AS datetime),
EndTime = DATEADD(
DAY,
CASE WHEN #StartTime > #EndTime THEN 1 ELSE 0 END,
CAST(#EndTime AS datetime)
)
),
hourly AS (
SELECT
n.number,
t.StartTime,
t.EndTime,
HStart = DATEADD(HOUR, DATEDIFF(HOUR, 0, t.StartTime) + n.number , 0),
HEnd = DATEADD(HOUR, DATEDIFF(HOUR, 0, t.StartTime) + n.number + 1, 0)
FROM timerange t
INNER JOIN master..spt_values n
ON n.number BETWEEN 0 AND DATEDIFF(HOUR, t.StartTime, t.EndTime)
WHERE n.type = 'P'
),
hourly2 AS (
SELECT
number,
HStart = CASE WHEN StartTime > HStart THEN StartTime ELSE HStart END,
HEnd = CASE WHEN EndTime < HEnd THEN EndTime ELSE HEnd END
FROM hourly
)
SELECT
StartHour = DATEPART(HOUR , HStart),
StartMinute = DATEPART(MINUTE, HStart),
EndHour = DATEPART(HOUR , HEnd ),
EndMinute = DATEPART(MINUTE, HEnd ),
StartTime = CAST(HStart AS time),
EndTime = CAST(HEnd AS time)
FROM hourly2
ORDER BY number
;
The output produced is this:
StartHour StartMinute EndHour EndMinute StartTime EndTime
----------- ----------- ----------- ----------- ---------------- ----------------
22 30 23 0 22:30:00.0000000 23:00:00.0000000
23 0 0 0 23:00:00.0000000 00:00:00.0000000
0 0 0 52 00:00:00.0000000 00:52:00.0000000
I'm currently trying to write a stored procedure that can compute the biweekly periods when a date is passed in as a parameter.
The business logic: the first Monday of the year is first day of the biweekly period.
For example in 2010:
period period_start period_end
1 2010-01-04 2010-01-17
2 2010-01-18 2010-01-31
3 2010-02-01 2010-02-14
....
26 2010-12-20 2011-01-02
Passing today's date of 2010-12-31 will return 26, 2010-12-20 and 2011-01-02. How to achieve this?
#Lamak did the hard part, figuring out the first Monday in the year (upvoted). I revised his routine a bit to take a datetime value, like so:
-- Return first Monday for the year being passed in
CREATE FUNCTION dbo.FirstMonday (#TargetDay datetime)
RETURNS DATE
AS
BEGIN
DECLARE #Return DATE
-- Set to first of its year
SET #TargetDay = dateadd(dd, -datepart(dayofyear, #TargetDay) + 1, #TargetDay)
;WITH Dates AS
(
SELECT #TargetDay AS DateVal
UNION ALL
SELECT DATEADD(d, 1, DateVal) AS DateVal
FROM Dates
WHERE DATEADD(d, 1, DateVal) < DATEADD(m, 1, #TargetDay)
)
SELECT #Return = MIN(DateVal)
FROM Dates
WHERE DATENAME(WEEKDAY,DateVal) = 'Monday'
RETURN #Return
END
GO
-- Test it
print dbo.FirstMonday(getdate())
print dbo.FirstMonday('Jan 1, 2010')
From there, it's just some datetime arithmatic:
DECLARE
#FirstMonday datetime
,#TargetDay datetime
,#BiWeek int
SET #TargetDay = getdate()
--SET #TargetDay = 'Jan 17, 2010'
-- Get the first Monday
SET #FirstMonday = dbo.FirstMonday(#TargetDay)
-- Calculate the bi-weekly period
SET #BiWeek = datediff(dd, #FirstMonday, #TargetDay) / 14
-- Print results
PRINT #BiWeek + 1
PRINT dateadd(dd, #BiWeek * 14, #FirstMonday)
PRINT dateadd(dd, #BiWeek * 14 + 13, #FirstMonday)
-- Or return them as a dataset
SELECT
#BiWeek + 1 Period
,dateadd(dd, #BiWeek * 14, #FirstMonday) PeriodStart
,dateadd(dd, #BiWeek * 14 + 13, #FirstMonday) PeriodEnd
This fails when you pick a day in the year that falls before the first Monday, as it returns the first biweekly period after that date. (Or does it fail? You did not specify what the proper period is for such dates... :)
However, as #HLGEM says, depending on what you are doing you are probably better off building and using some form of biweekly period lookup table, especially if you need proper handling of those early dates.
You can create a function to get the first Monday of a year. Something like this should work:
CREATE FUNCTION dbo.FirstMonday(#Year VARCHAR(4))
RETURNS DATE
AS
BEGIN
DECLARE #Return DATE;
WITH Dates AS
(
SELECT CONVERT(DATE,#Year+'0101') AS DateVal
UNION ALL
SELECT DATEADD(d, 1, DateVal) AS DateVal
FROM Dates
WHERE DATEADD(d, 1, DateVal) < DATEADD(m, 1, #Year+'0101')
)
SELECT #Return = MIN(DateVal)
FROM Dates
WHERE DATENAME(WEEKDAY,DateVal) = 'Monday'
RETURN #Return
END