SQL query not pulling correct year - sql

I have a query
SELECT
convert(varchar, dates, 101)
FROM
database
WHERE
dates BETWEEN '04/01/2015' AND '04/30/2015'
It returns all April dates but the problem is it is for every year (i.e. 2010, 2011, 2012, 2013, 2014, 2015). I think that it is not reading the last 2 digits of the year and just pulling everything from 2000 on. Am I correct in thinking this? How do I fix this?

Your dates column is likely not defined to be a date type. You can update the column type... or explicitly convert it in your query:
Select convert(varchar, dates, 101)
FROM database
Where convert(date,dates) BETWEEN '04/01/2015' and '04/30/2015'
The reason it would give you all April dates if your dates field was interpreted as a string of text is because all the April dates would be sorted together alphabetically. If it were properly interpreting your field to be a date, it would be able properly filter them.

You need to provide your dates in a standard format that SQL Server will understand correctly. See Correct way of specifying a given date in T-SQL.
For you it will be:
Where dates BETWEEN '20150401' and '20150430'

In tSQL this would work for you:
SELECT DATEPART(year, dates)
FROM [database]
WHERE DATEPART(MONTH, dates) = 4 AND DATEPART(year, dates)=2015;

Related

SQL issue: cannot construct data type date some of the arguments have values which are not valid

I am working on an Excel project where I use SQL query to extract some data from SQL Server 2012.
When I select the data without filters, everything works fine.
However, when I use the DATEFORMATPARTS formula below, I get this error:
Cannot construct data type date some of the arguments have values which are not valid
A.[Invoice date] is the correct date format.
WHERE
A.[Customer] NOT IN ('100', '398', 399)
AND A.[Item] LIKE '1%'
AND A.[Invoice date] >= DATEFROMPARTS(Year(DATEADD(yyyy, -1, GETDATE())), Month(DATEADD(yyyy, -1, GETDATE()) >) + 1, 1)
I've tried a lot of different stuff, but without luck.
Any guesses what is wrong in the above.
Thanks a lot in advance!
/ T
Thanks for the input
it was precisely the month: 12 + 1
that was the issue! thanks
You're going to have problems with that month calculation if you get a december and it adds a month to get month 13 of the year, this obviously isn't valid. If you want 11 months ago then do this;
DATEFROMPARTS(Year(DATEADD(YYYY,-1,GETDATE())),Month(DATEADD(mm,-11,GETDATE())),1)
Which (today, December 2016) returns '2015-01-01'
I believe > sign in the expression is a typo
Month(DATEADD(yyyy,-1,GETDATE()))+1
This is resulting 13 which is a invalid month so you are getting that error.
Removing > and +1 from Month part will fix your issue
select DATEFROMPARTS(Year(DATEADD(yyyy,-1,GETDATE())),Month(DATEADD(yyyy,-1,GETDATE())),1)
If you are trying to find last year last month first date then
select datefromparts(year(getdate())-1,12,1)

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'

Values over a time period

I would like to calculate a value in SQL that does the following:
if the user's inputted month parameter (I'm writing the SQL to aggregate information first then using SSRS) is 90 days or more past today (or the most recent data entry), then use the value for that month. Otherwise, if the month parameter is within 90 days of the report run date (or most recent data entry), use the most recent value that IS in fact 90 days past. For example, if I run the report in August and specify the month parameter as August, I will want the value from May. If I specify the month parameter as April, I want April's value since 90 days has gone by since then. Apologies if this isn't concise. I just would like some direction.
Cheers.
As suggested by #DanBracuk in the comments, you should probably take the parameter from SSRS and just update it based on the current date in your T-SQL code.
Say you have an SSRS parameter Parameters!Month.Value which gets passed to your stored procedure as #Month.
You can use GETDATE() and date functions like DATEDIFF() and DATEADD() to adjust #Month as required, e.g. in the stored procedure code something like:
select #Month = case when datediff(dd, #Month, getdate()) > 90
then #Month
else dateadd(dd, -90, #Month)
end
select *
from MyTable
where MyDate < #Month
Update the first statement to meet your requirements; they seem a bit ambiguous at this point - apologies if I haven't understood the issue completely.

Getting week number of date in SQL

Is there a way to get the week number of a date with SQL that is database independent?
For example to get the month of a date I use:
SELECT EXTRACT(MONTH FROM :DATE)
But the EXTRACT function doesn't know about weeks in SQL92.
Please pay attention to the fact that I want a solution that is database independent! Do not misinterpret this as a question regarding MS SQL Server.
There doesn't appear to be a single standard SQL function to extract the week number from a date - see here for a comparison of how different SQL dialects can extract different dateparts from date fields.
You can try this.
declare #date datetime
select #date='2013-03-15 00:00:00'
select 'Week No: '+ convert(varchar(10),datepart(wk,#date)) as weekno
Try this one :
SELECT DATENAME(yy,GETDATE())+RIGHT(DATENAME(wk,GETDATE()),2)
To understand DATENAME, please follow this link : sqltutorials.blogspot.be/2007/05/sql-datename.html and for the right, suite101.com/article/sql-functions-leftrightsubstrlengthcharindex-a209089 . There are examples to better understand ;-) It will work on MS and other sql servers normally ;-)
The only db independent solution I see is to get the number of days between today and Jan 1 of curr. year. Then divide it by 7 and round it up. There is 73 days from Jan 1 till today, which gives 10.43 as week number. The ISO week number is 11.
Correction: the number of days between last day of the current week and Jan 1 of curr. year. In this case the ISO week is 10, and 68/7 = 10 (rounded).
The best idea I found is
SELECT ROUND(((DAY(NOW())-1)/7)+1)
select (DATEPART(yyyy , CAST(GETDATE() AS datetime)) * 100 +
DATEPART(ww , CAST(GETDATE() AS datetime))) as week

SQL Query to Count Number of Days, Excluding Holidays/Weekends

I have a "workDate" field and a "receivedDate" field in table "tblExceptions." I need to count the number of days beteen the two. workDate always comes first - so, in effect, it's kind of like workDate is "begin date" and receivedDate is "end date". Some exclusions make it tricky to me though:
First, I need to exclude holidays. i do have a table called "tblHolidays", with one field - holidayDate. I have holidays stored up through next year, so maybe I can incorporate that into the query?
Also, most flummoxing is that work dates can never occur on weekends, but received dates can. So, i somehow need to exclude weekends when i'm counting, but allow for a weekend if the received date happens to fall on a saturday or sunday. so, if the work date is June 3rd, 2011, and received date is June 11th, 2011, the count of valid days would be 7, not 9.
Any help on this is much appreciated. Thanks!
Something like this should give you the number of days with the holidays subtracted:
select
days = datediff(day, workDate, receivedDate)
- (select count(*) from tblHolidays where holidayDate >= workDate and holidayDate < receivedDate)
from
tblExceptions
Note that the date functions differ between database systems. This is based on MS SQL Server, so it may need adapting if you are using some other database.
If you have a table full of dates to include (non-weekends, non-holidays, etc.) and you knew when the 'begin' date and the 'end' date is, then you can do something roughly like this:
select count(*) from tblIncludedDates where beginDateValue <= dateField and endDateValue >= dateField
to get the number of valid days between those dates.