SSRS graph: Retrieve values from different dates in SQL query - sql-server

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'

Related

SSRS date range parameter

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())

How to use - within like '%'% query

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())

SQL query to search

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'

SQL Date Subtraction Between Two Years

I am having an issue with a query I am trying to convert from MS Access. The query flags record for removal when it is older than 90 days but when I convert this query to sql server is is removing too many records.
UPDATE DT.SM_T_CountTotals
SET IsActive = 0
WHERE Convert(varchar, DT.SM_T_CountTotals.PostDate, 101) <
Convert(varchar, GetDate()- 90, 101)
When I run this query in MS Access I get a total of 3793 records that are flagged but in SQL server I get 69061 records that are flagged for removal. The GetDate()-90 value is correct at 10/26/2010 but it is flagging everything from this year to be removed.
I am sure it is something easy that I am overlooking. Help please?
I figured it out:
UPDATE DT.SM_T_CountTotals
SET IsActive = 0
WHERE DT.SM_T_CountTotals.PostDate < Convert(varchar, GetDate()- 90, 101)
You're comparing VARCHAR values, not DATEs.
101 converts to MM/DD/YY, so you're comparing month, then day, then year.
You should be using 112 (yymmdd)
Calculations between two dates can be easily done in the native data type rather than convert it to string. One can (and you have) get incorrect answers from such conversions.
Use DateDiff in the where clause to get the records that are more than 90 days old.
http://msdn.microsoft.com/en-us/library/ms189794.aspx
UPDATE DT.SM_T_CountTotals
SET IsActive = 0
WHERE ABS (DATEDIFF (dd, Getdate(), DT.SM_T_CountTotals.PostDate)) > 90

What's the best way to perform math on a floored date in SQL Server?

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.

Resources