I have a table column in SQL 2012 called transitiontime that contains dates and times in the format 2017-02-02 21:00:34.847. I'm trying to query all results within the last 3 months, which I would think would just require me to look for 2017-02, or something to that effect. However if I leave the hyphen in, the query fails.
Examples:
WHERE transitiontime like '%2017%' <- works but returns all values from this year
WHERE transitiontime like '%2017-02%' <- Does not work at all
WHERE transitiontime like '%2017%02%' <- Works but pulls in anything with 2017 and 02 in it, even if 02 is just in the time.
I would love to get the past 3 months in one query, but right now I'd like to just be able to pull from 1 month.
I'm assuming, since you are using the keyword "like", that the field "transitiontime" is a char oder varchar field?
Change the type of the field to DateTime and use the following query, to get all results for the last three months (applying to SQL):
SELECT * FROM table WHERE transitiontime >= DATEADD(month, -3, GETDATE())
Related
I have a report in SSRS 2016 that contains one SP which has a date field called startdate. I'd like to create a parameter where the user can select between two ranges: startdate >='2017'or startdate < '2017'. This seems like it should be simple, but I can't see to find an easy way to do this.
I've tried to create a parameter in SSRS where I chose "Specify Values" and manually added these values but I get an error that the "expression references the parameter "startdate" which does not exist in the Parameters collection.
I'm sure I can create this by creating a stored procedure with these dates, but that seems like more work than is needed.
Does anyone know of a better way to do this?
If you are looking to have a parameter that has two options, 0 - Before 2017, and 1 - After 2017 then you should just create a Date parameter which has two options, Before 1/1/2017 in the label field with a 0 in the value field and After 1/1/17 in the label field with a 1 in the value field. Then in your report you just have to filter your data based upon the 1 or 0 value.
For example:
DECLARE #DateFilter INT = 1
IF ( #DateFilter = 0 )
BEGIN
SELECT * FROM dbo.MyTable t
WHERE t.DateFilter < '1/1/17'
END
IF ( #DateFilter = 1 )
BEGIN
SELECT * FROM dbo.MyTable t
WHERE t.DateFilter >='1/1/17'
END
I don't know why you would filter your data this way. I recommend to use Larnu's suggestion that you have two parameters, a Start Date and an End Date. Otherwise this could return a lot of rows for the second option as time goes on.
Add a couple of parameters in SSRS say, FromDate and ToDate and make its data type as Date/Time.
You can specify the default values for these parameters using DateAdd functions and samples give below:
Today:
=Today()
last week from today:
=DateAdd(DateInterval.Day, -7,Today())
You can add/reduce year, quarter month etc. in a similar way as shown below. Just change the number to the required length
=DateAdd(DateInterval.Year,-1,Today())
=DateAdd(DateInterval.Quarter,-1,Today())
=DateAdd(DateInterval.Month,-1,Today())
=DateAdd(DateInterval.DayOfYear,-1,Today())
=DateAdd(DateInterval.WeekOfYear,-1,Today())
=DateAdd(DateInterval.WeekDay,-1,Today())
=DateAdd(DateInterval.Hour,-1,Today())
=DateAdd(DateInterval.Minute,-1,Today())
=DateAdd(DateInterval.Second,-1,Today())
I am using the following query to retrieve snapshot values from 4 different dates: -1 day (latest), -2 days, -3 days and -40 days (not yet implemented).
SELECT [SnapshotDate]
,[SnapshotKey]
,[info1]
,[info2]
,[info3]
FROM [Database].[dbo].[Values]
WHERE [SnapshotDate] >= DATEADD(day,-3, GETDATE())
AND [SnapshotKey] = 'Some text here'
This results in the following graph:
The query is not quite right firstly since it is showing 4 values and should only be showing 3 at this point. Secondly I would like to show the last snapshot from 40 days ago as shown in the graph.
I have tried a few different queries but have not managed to figure out how to do this properly.
[SnapshotKey] = SELECT DATEADD(day,-40,getdate())
The above query gives me the correct answer in theory. However, when I use this in my query there is no result. I believe this might be due to not having a date conversion or the fact that I'm using "day" in my query. I'm not sure.
Any suggestions?
EDIT:
I also tried using the following with no luck (no result):
CONVERT(date, [SnapshotDate]) = CONVERT(date, DATEADD(day,-40, GETDATE()))
I'm not sure what your date values are but I'm guessing this report was run on 2nd May.
If this is correct then you need to change the range to exclude where the difference in dates is zero. Personally I use DATEDIFF in situations like this as it's easier to visualise for me.
Try changing the where clause to something like this.
WHERE (DATEDIFF(day, getdate(),[SnapshotDate]) BETWEEN -3 AND -1
OR DATEDIFF(day, getdate(), [SnapshotDate]) = -40)
AND [SnapshotKey] = 'Some text here'
I have 2 x fields T1.period and T1.year both have data type smallint
Using SQL Management Studio 2014 how may I Concatenate them AND return result as a DATE type?
Also, T1.period has values 1 to 12 how may I pad this out to 01 to 12 ... or will changing to date type sort this out?
Much appreciated!
Sample data ...
period yr
1 2015
2 2009
12 2009
11 2010
10 2011
Result will be ...
Date
01/01/2015
01/02/2009
01/12/2009
01/11/2010
01/10/2011
Thanks!
Looks terrible struggling to get it into lists - sorry :(
Converting Your Values The Old Fashioned Way
Assuming that your t1.period value actually just represents a month, you could consider just converting your values to strings and then converting that concatenated result into a date via the CAST() function :
SELECT CAST(CAST(t1.year AS VARCHAR) + '-' + CAST(t1.period AS VARCHAR) + '-1' AS DATE)
This will build a string that looks like {year}-{month}-1, which will then be parsed as a DATE and should give you the first date of the given month/year.
Using The DATEFROMPARTS() Function
SQL Server 2012 and above actually support a DATEFROMPARTS() function that will allow you to pass in the various parts (year, month, day) to build a corresponding DATE object, with a much easier to read syntax :
SELECT DATEFROMPARTS(t1.year,t1.period,1)
Additionally, if you needed a DATETIME object, you could use DATETIMEFROMPARTS() as expected.
i am new at sqlserver and i just started learning it , and i have a question .
**i want an SQL query that can bring up all rows that were added in the past 6 months. in table 'users' the date is in field 'joined' but its in UNIX time stamp format
**and i want then like another SQL query the same as above but it also with the results sets the field 'activate' in each row to 'yes'
i tried that code :
select * from users where time_of_post is like '07/**/2011'
** = anyday but i can`t implement it right .
Thank you a lot for your help in advance .
select *
from users
where datediff(mm, time_of_post, getdate()) <= 6
What you want to use is the DATEDIFF() function, and get the difference between today's day (GETDATE()) and the stored dates (time_of_post). If that is less than or equal to 6 months (as denoted by the first parameter, mm) then that should be what you're looking for.
EDIT:
If you're looking to use this logic for an UPDATE, you'd do something like this:
update users
set activation = 'yes'
where datediff(mm, time_of_post, getdate()) <= 6
and activation <> 'yes'
This is related to Floor a date in SQL server, but I'm taking it one step further:
I'm writing a query on a SQL Server table and I want to get all records for the current calendar year and the previous calendar year. So, right now, I'd want a query to return all records between January 1st, 2008 and today. But come January 1st, 2010, I want it to return records no older than 2009.
Essentially, I want to floor the current date to the beginning of the year and then subtract 1.
After rummaging through some SQL Server documentation, I came up with this:
WHERE create_date >= CAST((CAST(YEAR(GETDATE()) AS int) -1) AS varchar)
but it feels kind of ugly. Is there a better way?
Why not just use the year function on create_date as well?
WHERE YEAR(create_date) >= (YEAR(GETDATE()) -1)
This assumes (as you did) that there are no records in the database greater than today's date
I would suggest assigning a variable with the date lastyear-01-01, either by making an UDF for it, or something like
DECLARE #startOfLastYear DATETIME
SET #startOfLastYear = CAST(YEAR(GETDATE()) - 1 AS VARCHAR) + '-01-01'
Then do the query:
WHERE create_date >= #startOfLastYear
Because of two reasons:
Using YEAR() or any other function
on data from tables (i.e.
YEAR(create_date)) makes indices
unusable and decreases the
performance of the query
The variable name tells exactly what it is, and reading the code is easier.