Displaying specific SQL Datetime - sql

I'm trying to display a start and end time for a SQL report. I always want to display the previous month period to look like:
Start Time: Aug 1st 2014 00:00:00
End Time: September 1st 2014 00:00:00
If the report was run in Oct it would give Sept1-Oct1. Not sure how to actually display that as a Datetime variable?

In a DATETIME format, that would be
SELECT
DATEADD(month, DATEDIFF(month, 0, GETDATE())-1, 0) AS StartTime,
DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0) AS EndTime
If you want to play around with character formats, you can do a bunch of things, like
SELECT
DATENAME(MONTH,StartTime) + ' ' + CAST(YEAR(StartTime) AS VARCHAR(4)) + ' - ' + DATENAME(MONTH,EndTime) + ' ' + CAST(YEAR(EndTime) AS VARCHAR(4)),
LEFT(DATENAME(MONTH,StartTime),3) + ' ' + CAST(YEAR(StartTime) AS VARCHAR(4)) + ' - ' + LEFT(DATENAME(MONTH,EndTime),3) + ' ' + CAST(YEAR(EndTime) AS VARCHAR(4))
FROM
(
SELECT
DATEADD(month, DATEDIFF(month, 0, GETDATE())-1, 0) AS StartTime,
DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0) AS EndTime
) dt

I apologize if i misunderstood but is this what you are looking for?
SELECT CAST(DATEADD(MONTH,-1,[date]) AS VARCHAR(12)) + '-' + CAST([date] AS VARCHAR(12)) FROM table
If you were to insert into your table a SMALLDATETIME such as
'2014-09-23 10:28:00'
then what would be produced is:
'Aug 23 2014 -Sep 23 2014 '

DATE_SUB(Date,INTERVAL 1 MONTH) AS PastMonth
would display one month prior to Date

Related

Conversion failed when converting the varchar value '2 year -2 month 21 day' to data type int

I am trying to find out for how long employees have been working for the company and I should also find out if any of the employees have a resignation date.
But I don't have data for this right now, therefore value of this column in my database is Null. But i consider in my sql when it's happened take Resignation Date instead current time But for now take work start date and current time. my theory is if the column resignation date is null, take "Current Date - Work start date", else
should it take resignation date - Work start date.
I wrote a SQL query for this theory and it's working fine but when I tried return for ex year month day for how long employees working I got a problem which is:
a ) I struggled with this error for hours and I also tried convert those lines, I thought its should be converted but it's not working well so, when I run my main query, I get this error:
> Msg 245, Level 16, State 1, Line 1
> Conversion failed when converting the varchar value '2 year -2 month 21 day' to data type int.
My main query looks like this:
**--- sql for how long employees work with year month day ----**
CASE
WHEN Users.ResignationDate IS NOT NULL
THEN DATEDIFF(YEAR, WorkStartDate, ResignationDate)
ELSE CAST(DATEDIFF(yy, WorkStartDate, GETDATE()) AS varchar(4)) + ' year ' +
CAST(DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy, WorkStartDate, GETDATE()), WorkStartDate), GETDATE()) AS varchar(2)) + ' month ' +
CAST(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy, WorkStartDate, GETDATE()), WorkStartDate), GETDATE()), DATEADD(yy, DATEDIFF(yy, WorkStartDate, GETDATE()), WorkStartDate)), GETDATE()) AS varchar(2)) +' day' END as Ancinitet,
Paychecks.DepartmentName AS Afdelinger
FROM dbo.Paychecks INNER JOIN dbo.Users ON Users.Id=Paychecks.UserId
WHERE Users.CustomerId=214 order by Users.FirstName;
A case expression returns a single value -- and a single type. Yours is returning two different types, and SQL Server decides that the appropriate return type is the first one, an integer.
Just cast to a string:
(CASE WHEN Users.ResignationDate IS NOT NULL
THEN CAST(DATEDIFF(YEAR, WorkStartDate, ResignationDate) as VARCHAR(255))
ELSE (CAST(DATEDIFF(year, WorkStartDate, GETDATE()) AS varchar(4)) +' year ' +
CAST(DATEDIFF(month, DATEADD(year, DATEDIFF(year, WorkStartDate, GETDATE()), WorkStartDate), GETDATE()) AS varchar(2)) +' month ' +
CAST(DATEDIFF(day, DATEADD(month, DATEDIFF(month, DATEADD(year, DATEDIFF(year, WorkStartDate, GETDATE()), WorkStartDate), GETDATE()), DATEADD(year, DATEDIFF(yy, WorkStartDate, GETDATE()), WorkStartDate)), GETDATE()) AS varchar(2)) +' day'
)
END) as Ancinitet,
I suspect there is a better way to do what you want. If that is of interest, ask another question with sample data and desired results.
What's wrong with this?
datediff(year, workStartDate, isNull(resignationDate, getDate()))
You'd be better off using weeks instead of months, since a week always contains 7 days. You could also use a 30 day month which will generally get you close but your days may be off by a couple.
DECLARE #StartDate DATETIME = '20151115',
#EndDate DATETIME = GETDATE();
SELECT YearWeekDay = CONCAT(DATEDIFF(DAY, #StartDate, #EndDate) / 365, ' year ', DATEDIFF(DAY, #StartDate, #EndDate) % 365 / 7, ' week ',
DATEDIFF(DAY, #StartDate, #EndDate) % 365 % 7, ' day'
),
YearMonthDay = CONCAT(DATEDIFF(DAY, #StartDate, #EndDate) / 365, ' year ', DATEDIFF(DAY, #StartDate, #EndDate) % 365 / 30, ' month ',
DATEDIFF(DAY, #StartDate, #EndDate) % 365 % 30, ' day '
),
YWDHMS = CONCAT( DATEDIFF(SECOND, #StartDate, #EndDate) / 86400 / 365, 'y ', DATEDIFF(SECOND, #StartDate, #EndDate) / 86400 % 365 / 7, 'w ',
DATEDIFF(SECOND, #StartDate, #EndDate) / 86400 % 365 % 7, 'd ', DATEDIFF(SECOND, #StartDate, #EndDate) % 86400 / 3600, 'h ',
DATEDIFF(SECOND, #StartDate, #EndDate) % 3600 / 60, 'm ', DATEDIFF(SECOND, #StartDate, #EndDate) % 60, 's '
);
Output:
StartDate EndDate YearWeekDay YearMonthDay YWDHMS
2015-11-15 2017-02-22 15:11:34.123 1 year 14 week 2 day 1 year 3 month 10 day 1y 14w 2d 15h 11m 34s

SQL - Email query range

I have a sql job which queries the database. The job is scheduled to run every 24 hours and it sends out an email with required data which has a query range from 07:30 today to 07:30 the previous day. Here is the code for the heading of my email :
INSERT INTO #ReportContentBuilder VALUES('<h4>Query Range : ' + DATENAME(WEEKDAY,#StartTimestamp)
+ ', ' + CONVERT(varchar, #StartTimestamp, 106) + ' ' + CONVERT(varchar, #StartTimestamp, 108)
+ ' (UTC) to ' + DATENAME(WEEKDAY,#EndTimestamp) + ', ' + CONVERT(varchar, #EndTimestamp, 106)
+ ' ' + CONVERT(varchar, #EndTimestamp, 108) + ' (UTC)</h4>')
Here is the value I have for #StartTimestamp:
SET #StartTimestamp = CAST((CONVERT(varchar(11), DATEADD(DAY, -1, #EndTimestamp), 106) + ' 07:30') as datetime)
Here is the expected output for my email heading :
Query Range : Wednesday, 19 Nov 2014 07:30:00 (UTC) to Thursday, 20 Nov 2014 07:30:00 (UTC)
My question is what value do I use for #EndTimestamp??
If I use GETUTCDATE() and the job runs 2 mins late then the range is incorrect. I also don't want to hardcode it because of the changes needed for daylight savings each time.
The trick is that the "dynamic" part is the difference between current time (GETUTCDATE()) and 7:30 . So with #timeDiff you can handle this dynamic part of the ecuation. Try this (replace last select with your needed insert; I only tested the output):
DECLARE #StartTimestamp datetime
DECLARE #EndTimestamp datetime = GETUTCDATE()
DECLARE #timeDiff time
SET #timeDiff = CONVERT(time, (#EndTimestamp - cast('1900-01-01 07:30:00.000' as datetime)))
SELECT #EndTimestamp = dateadd(second,
datepart(hour,#timeDiff) * -3600 +
datepart(minute,#timeDiff) * -60 +
datepart(second,#timeDiff) * -1,
#EndTimestamp)
SET #StartTimestamp = DATEADD(DAY, -1, #EndTimestamp)
SELECT #StartTimestamp, #EndTimestamp
SELECT '<h4>Query Range : ' + DATENAME(WEEKDAY,#StartTimestamp)
+ ', ' + CONVERT(varchar, #StartTimestamp, 106) + ' ' + CONVERT(varchar, #StartTimestamp, 108)
+ ' (UTC) to ' + DATENAME(WEEKDAY,#EndTimestamp) + ', ' + CONVERT(varchar, #EndTimestamp, 106)
+ ' ' + CONVERT(varchar, #EndTimestamp, 108) + ' (UTC)</h4>'

How can I use GETDATE() to get month and year from the past month?

How can I get it to one statement that can get me
last month and this year?
I have a INSERT INTO and in a column report_date [datetime]
insert into table_a (report_date) values ( ??);
i want to show this past month and year,
So for example today is 4/21/2014
so it would show 3/2014 in the column
If today was MAY 1 2014 , it would show 4/2014?
Is this possible or does it have to have a day?
You're looking for the DATEADD function:
SELECT DATEPART(month, DATEADD(month, -1, GETDATE()), DATEPART(year, DATEADD(month, -1, GETDATE())
If you are trying to get 'last month' with 'this year' you could do:
SELECT CAST(
CAST(YEAR(GETDATE()) AS VARCHAR) + '-' +
CAST(MONTH(GETDATE())-1 AS VARCHAR) + '-' +
CAST(DAY(GETDATE()) AS VARCHAR)
AS DATETIME)
But then in JAN 2015, it would return DEC 2015.
If you just want last month, use the 'DATEADD' function.
SELECT DATEADD(MONTH, -1, GETDATE())

Pulling a month of rows in SQL Server based on a dynamic day

I have a table in SQL server that looks like this (there are other fields, but there are the only 2 I care about):
-----------------------------------------
| DraftDay (int)| MonthlyFee (money)|
-----------------------------------------
1 18.75
2 15.25
2 15.25
3 15.25
3 28.12
4 15.25
4 3.75
4 18.19
5 12.75
6 13.80
6 14.25
... ...
... ...
What I am trying to do is write a query that will group by DraftDay and sum the MonthlyFee field. Simple enough. But the hard part is, I need to get the date of one month ago, plus one day and pull the days from that day to the current day. For example, if today is 4/3/2014, then I need to pull all days between 3/4/2014 and 4/3/2014. My result set should look like this:
3/4/2014 37.19
3/5/2014 12.75
3/6/2014 28.05
... ...
... ...
4/1/2014 18.75
4/2/2014 30.50
4/3/2014 43.37
I have created this query:
SELECT
CAST(CAST(DATEPART(MONTH, DATEADD(DAY, 1, DATEADD(MONTH, -1, GETDATE()))) AS VARCHAR(2)) + '/' +
CAST(CASE WHEN EftDraftDay>28 THEN 28 ELSE EftDraftDay END AS VARCHAR(2)) + '/' +
CAST(DATEPART(YEAR, DATEADD(DAY, 1, DATEADD(MONTH, -1, GETDATE()))) AS VARCHAR(4)) AS DATETIME) AS DraftDate,
SUM(MonthlyPayment) AS MonthlyPayment FROM dbo.Advertiser
WHERE IsDeleted=0
AND IsPaidInFull=0
AND IsAdvertiserActive=1
AND EftDraftDay>0
AND (CAST(CAST(DATEPART(MONTH, DATEADD(DAY, 1, DATEADD(MONTH, -1, GETDATE()))) AS VARCHAR(2)) + '/' +
CAST(CASE WHEN EftDraftDay>28 THEN 28 ELSE EftDraftDay END AS VARCHAR(2)) + '/' +
CAST(DATEPART(YEAR, DATEADD(DAY, 1, DATEADD(MONTH, -1, GETDATE()))) AS VARCHAR(4)) AS DATETIME)) >=
CAST(CAST(DATEPART(MONTH, DATEADD(DAY, 1, DATEADD(MONTH, -1, GETDATE()))) AS VARCHAR(2)) + '/' +
CAST(DATEPART(DAY, DATEADD(DAY, 1, DATEADD(MONTH, -1, GETDATE()))) AS VARCHAR(2)) + '/' +
CAST(DATEPART(YEAR, DATEADD(DAY, 1, DATEADD(MONTH, -1, GETDATE()))) AS VARCHAR(4)) AS DATETIME)
GROUP BY
CAST(CAST(DATEPART(MONTH, DATEADD(DAY, 1, DATEADD(MONTH, -1, GETDATE()))) AS VARCHAR(2)) + '/' +
CAST(CASE WHEN EftDraftDay>28 THEN 28 ELSE EftDraftDay END AS VARCHAR(2)) + '/' +
CAST(DATEPART(YEAR, DATEADD(DAY, 1, DATEADD(MONTH, -1, GETDATE()))) AS VARCHAR(4)) AS DATETIME)
Because today's date is 4/17/2014, I should be getting results back from 3/18/2014 thru 4/17/2014. The results I'm getting back are only from 3/18/2014 thru 3/28/2014. How can I also add 4/1/2014 thru 4/17/2014 into my result set? I thought about a UNION, but those don't seem to work well with GROUP BY's.
After trying to figure this out and looking at my query, I think I am totally over engineering this. My query looks so complex for such a simple thing. Can anyone please help me out with this?
Try this:
declare #lastmonth date = convert(date,dateadd(day,1,dateadd(month,-1,getdate())))
declare #thismonth date = convert(date,getdate())
select
case
when draftday < datepart(day,#thismonth)
then convert(date, cast(datepart(yyyy,#thismonth) as varchar) + right('00'+cast(datepart(MM,#thismonth) as varchar),2) + right('00'+cast(cast(draftday as varchar) as varchar),2))
else convert(date, cast(datepart(yyyy,#lastmonth) as varchar) + right('00'+cast(datepart(MM,#lastmonth) as varchar),2) + right('00'+cast(cast(draftday as varchar) as varchar),2))
end,
sum(monthlyfee) from tbl
group by draftday
This will treat days before current day as belonging to current month, and others as from last month, and then sum up. Please let me know if this is doing what you expect.
I'd use the Calendar table (http://www.dbdelta.com/calendar-table-and-datetime-functions/), something like this:
declare #d datetime ='20140403'
select c.CalendarDate, sum(#t.MonthlyFee)
from calendar c
left join #t on c.CalendarDay = #t.DraftDay
where CalendarDate between dateadd(month, -1, #d)+1 and #d
group by c.CalendarDate

convert datetime to display full month

I have searched and i cannot seem to find the answer. I have tried using different styles, but none of them give me exactly what i want.
I am trying to convert a datetime, that I have calculated. However I need it to display the full month.
SELECT CONVERT(VARCHAR(25),DATEADD(dd, #codelife, getdate()),107)
the above line works fine, EXCEPT it displays the date like
Feb 27, 2014
I need it to display date like
February 27, 2014 etc.....
any suggestions?
Nathan's answer seems solid, however if you're using SQL Server 2012 you can make use of the FORMAT() function:
SELECT FORMAT(GETDATE(),'MMMM dd, yyyy')
Or in your case:
SELECT FORMAT(DATEADD(dd, #codelife, getdate()),'MMMM dd, yyyy')
I always use http://www.sql-server-helper.com/tips/date-formats.aspx as my reference
SELECT DATENAME(MM, GETDATE()) + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9) AS [Month DD, YYYY]
I would declare your date as a variable and do something like:
DECLARE #myDate DATETIME
SET #myDate = DateAdd(dd, #codelife, getdate());
SELECT DATENAME(MM, #myDate) + RIGHT(CONVERT(VARCHAR(12), #myDate, 107), 9) AS [Month DD, YYYY]
You may have to do it in 2 steps.
DECLARE #codelife INT = 120
DECLARE #codedate DATETIME = (SELECT (DATEADD(D, #codelife, GETDATE())))
SELECT DATENAME(MM, #codedate) + SUBSTRING(CONVERT(VARCHAR(25), #codedate, 107), 4, 25)
SELECT DATENAME(MONTH, GETDATE())
+ RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9) AS [Month DD, YYYY]
OR Date without Comma Between date and year, you can use the following
SELECT DATENAME(MONTH, GETDATE()) + ' ' + CAST(DAY(GETDATE()) AS VARCHAR(2))
+ ' ' + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [Month DD YYYY]
I answered the same question a couple of days ago have a look here sql server Get the FULL month name from a date