Using CONVERT to check for specific day, results in conversion failed if day does not exist - sql

In SQL Server I am writing a query to calculate some time between certain user events, and for this I need to run an aggregate query for set days for an event. An event can run on multiple days, and for the data I am using to validate my query, there is data for Feb 27th, Feb 28th, but the event goes from Feb 25th - March 1st.
I am only using a subset of the data to validate the query, there will be a lot more data which matches more days, or less days.
So I am trying to add an IF check to my query to only run the aggregate if data exists for that specific day, like so:
IF EXISTS(SELECT 1 FROM sourcedata SD
JOIN #dwellTime DT ON SD.badgeid = DT.badgeid
WHERE SD.eventid = 1234
AND CONVERT(date, SD.DateAdded, 110) = '2018-02-29')
But as I say, my #dwellTime data does not have data for 29th, and when it tries to do the convert, no data is there to convert and I receive the
Conversion failed when converting date and/or time from character string.
error.
How can I check for a specific day being in the data?
DateAdded is a datetime column.

I believe the problem is that "2018-02-29" is not a valid date. This year, February had only 28 days. The next leap year is 2020.
So, if you use a valid date for the comparison, you shouldn't have a problem.
If you want to include invalid dates, then you can make the comparison as a string rather than a date. Or, you can use try_convert(date, '2018-02-29'). This will return NULL.

Related

How to get the data for the last 12 months and split and month-wise in HIVE?

Table format for the date column is "yyyyMMdd" and I'm using the following functions to convert into standard format so that HIVE day, months and year can be performed to get the respective values.
(from_unixtime(unix_timestamp(cast(created_day as STRING) ,'yyyyMMdd'), 'yyyy-MM-dd'))
To get the current year data, I would subtract the year obtained from all the records with the year returned by the current date and if it return zero, then it falls in this year.
(year(current_date()) - year(from_unixtime(unix_timestamp(cast(created_day as STRING) ,'yyyyMMdd'), 'yyyy-MM-dd'))) = 0
Problem: If the current date falls in January, I would get only January data month, but i need to get the data from February(last year) to January(current year)?
Also I need to scale this to obtain the last 24 months.
I always set my date range parameters outside of Hive and pass them as arguments as this lends itself to reproducibility and testability.
select <fields> from <table> where created_day between ${hiveconf:start_day} and ${hiveconf:end_day}

datepart in sql on year change

I am using datepart function in SP. It is used to compare week and year of specified date.
Now my query arise as new year starts. I have one table called 'Task' and it is storing tasks date wise. Now When I execute SP with DATEPART(YY,'2016-01-05') . It is giving proper 2016's data. But I execute it with DATEPART(ISOWK,'2016-01-05') , it is giving 2015's data also with 2016's data.
I want data from 28th dec,2015 to 2nd jan,2016. Data of the week. And I am not able get data of 1st and 2nd Jan in that. Please help me with this.
Thanks,
ISOWK return the week number
You are trying to get date from 2015-12-28 to 2016-01-02.
The week number of 2015-12-28 is 53 and 2016-01-02 is 53
If you already have your start and end dates decided then you could use a simple query as shown below to filter on date range.
When mentioning date string in your query make sure you stick to this format :yyyymmdd which SQL Server will automatically understand. You don't need DATEPART to get records between two dates.
Query for filtering on a date range
SELECT TaskID, TaskDescription
FROM Tasks
where TaskDate between '20151228' and '20160102'
Another query you can use for date range filtering
SELECT TaskID, TaskDescription
FROM Tasks
where TaskDate >= '20151228' and TaskDate <= '20160102'

SQL Query that rund monthly on a fixed day range

I have an SQL query I need to run once a month.
The data set the query produces always has to be from the 11th of the month before to the 10th of the current month.
I now manualy run the query in the fews days after the 11th day of the month manually adjusting the date range in my where statement:
for example...
Where Column A is greater than 10/10/2015 and less than 12/11/15
I was hoping there would be a statement I could add to my query to automatically find the 11th day of the last month and the 10th of the current month. This way I could schedule the query and automatically email the results.
You should be able to use the following within your query: -
CONVERT(date,FORMAT(GETDATE(),'yyyy-MM')+'-10')
(for the 10th of this month)
and
CONVERT(date,FORMAT(DATEADD(m,-1,GETDATE()),'yyyy-MM')+'-11')
(for the 11th of last month).
Try to look out the MONTH() function in your working DBMS. In MySQL and MSSQL it returns a number (1 been january) corresponding to the current month that your system is (you may check if it's date is updated).
With this function you can subtract 1 to get the last month, having to do some logic when the current one is January, hence 1. Since now you should get 12 (december) intead of 0 (an error).
Cheers, mate!

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

How to get month within a range vb2010

I just don't know how to go about this.
I designed a program that uses MS Access as its database. I have a field for month and year (the field data type is text) where user can register details. The program will register the month and year the user have chosen e.g month= September, year=2011.
My problem now is how to chose a range of data to view by the user using the month and year as a criteria e.g the User may want to view data range from (September 2011 to July 2013).
I couldn't figure out even how to try. Help will be highly appreciated.
Perhaps you could change your application logic to store the month and year as their respective numbers rather than text and change the field data types to numeric.
You could then construct a DateTime object from them, for example September would be 9 and you could use code like the following:
var startDate = new DateTime(year, month, 1); // get year and month as integers from database, uses the first as the date
var endDate = new DateTime(year, month, 10); // change the date but keeps the month and year the same
var endDate2 = startDate.AddMonths(1); // adds 1 month to the date
Alternatively, you could try using a calendar control to allow the user to select two dates instead of building it from a number of fields. Depending on what you are using this could be achieved a number of ways, for example in ASP.Net or WPF you could use two calendar controls and just use their SelectedDate properties as your range.
A range is from a startpoint until an end point. For the startpoint you can add automatically the first of Month. For the endpoint is it more complicated because there is no fix endpoint. What you can do is following:
Write an array that contains for each month the days (e.g. 30 or 31). Except for Febrauary there is a fix pattern.
for Febrauary use the selected year to check is the year a leap year or not. If not add 28, else add 29.
After that create the date string for your SQL:
Startdate 1.9.2011. Do for the entdate the same.
After that, I think you can use the keyword between in your SQL query.
You can assume that everything is entered on the first day of each month. I would pull the information using a query to the database.
select * from [tablename] where DateSerial([colYear], [colMonth], 1) between DateSerial([fromYear], [fromMonth], 1) and DateSerial([toYear], [toMonth], 1)
In this question are some ways to do this:
First. Filter the dates in a range assuming that you use a date like '07-12-2012'
i.e. September 2011 to July 2013
Where DateColumn > '09-01-2011' and DateColumn < '07-31-2013'
OR
Specify a Date and a Year
Where month(DateColumn)='1' and year(DateColumn)='2016'
Note:
There are many ways to do this.
You can Manipulate your statement depending on your desired output.