two sub query in sql - query-optimization

I am working on an application in which I have to retrieve min and max date from DATETIME Column and then set min and max value to JSlider.
My Date format present in database : 2017-06-22T03:16:26Z
But I only want date in two formats 20170622031626 AND 20170622
I have tried some sql query but doesn't get the required results.
Here are two query I am using :
SELECT DISTINCT( REPLACE("DATETIME",'-','') ) FROM CDR WHERE DATETIME = (SELECT MIN(DATETIME) FROM CDR)
OUTPUT: 20170501T00:00:00Z
select min(replace(replace(replace(replace("DATETIME",'-',''),'T',''),'Z',''),':','')) FROM CDR
OUTPUT: 20170501000000
The second query gives the one of the required results but how can I get only 20170501 ?
Any idea how can I achieve the required results ??

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

Microsoft SQL Server - Open Query where > date

I am trying to run a select using openquery with filtering result by date, but I have problem with using the date after where clause.
Ideally I would like to be able to pass a variable
set #d = dateadd(day, -30, getdate())
but for the sake of example I will try to use specified date :
Example:
select *
from OPENQUERY([Linked_Server], 'select id, name from Users where LastModifiedDate > ''2017-01-01''')
This returns an error:
INVALID_FIELD:
select id, name from Users where LastModifiedDate > '2017-01-01'
value of filter criterion for field 'LastModifiedDate' must be of type dateTime and should not be enclosed in quotes".
It works ok if I use for example istrue = true, but comparing dates seems to be the problem.
Can someone please advise me on this ?
It looks like you're querying a linked server that is not standard SQL Server but is instead Salesforce which uses SOQL which has a specific format for date and datetime literals. The correct format for date filters in Salesforce is:
WHERE LastModifiedDate > 2017-01-01T00:00:00Z
So your full SQL should be:
SELECT *
FROM OPENQUERY(
[Linked_Server],
'SELECT id, name FROM Users WHERE LastModifiedDate > 2017-01-01T00:00:00Z')
WE use a lot of Open queries here and we've stumbled into that kind of scenario. What we have done in the past is this:
CONVERT(VARCHAR(11),#d,101)
OR
CONVERT(VARCHAR(25),#d,126)
This already converts the date into the format DavidG posted there.
Also, to double check if the query is coming out correctly, we assign the query text into a variable and then we use the print to show the variable, that print which is just simple text that will show on your Message tab alongside your resultset tab. As long as the Where clause shows with only two single quotations, the query you have should work, just in case of doubt, copy the message and run it separately by replacing all doubled single quotations into one single quotation only.
What I had in my message tab on WHERE clause was something like that:
WHERE thisdate BETWEEN ''02/27/2017'' AND ''2017-02-27T23:59:59.990''

Get date from int (YYYYMMDD)

By doing a mistake a few months ago I got myself in a situation, where I have to find a workaround for the following problem:
I am saving dates as integer in a common format inside my SQL Server database (YYYYMMDD). I want to have my select statement giving me the integer in a format, that looks like a date (or even is in a true date type) to the user, so I can use the received datatable directly as datasource for my DataGridView.
I do not want to use clientside formatting
Let's call the table myTable and the integer/date column myIntDate
myIntDate can be NULL
sample myIntDate-value : 20160803 for the 3rd of August 2016
Select cast(cast(20160729 as varchar(10)) as date)
Returns
2016-07-29
Or
Select cast(left(20160729,8) as date)

How to convert MySQL to SQL Server query to display proper date from timestamp?

I need the following query below converted for SQL Server 2005, so please let me know what I should change since SQL Server doesn't support DATE_FORMAT()
How it should look converted in SQL Server so I can display proper date on my website instead of timestamp (example: 1382016108 to be 2013-06-22 10:53:22) ?
SELECT DATE_FORMAT(TimeTransfer,'%Y-%m-%d %h:%i:%s')
FROM PREMIUM where strAccountID = ?, $_SESSION['strAccountID']);
EDIT: I checked the CONVERT() function but couldn't find out how it should be exactly in my case with my query. Help is greatly appreciated.
This will work:
SELECT CONVERT( VARCHAR(20) -- Make sure the output string is long enough
, CAST('1970-1-1' As DateTime) -- The Base Date
+ CAST(TimeTransfer As Float)/(24*60*60)
-- Scale UTC (seconds) to TSQL datetime (days)
-- by dividing by the number of seconds in a day
, 120) -- The format that you want
Check the Convert function. It allows you to give format to a datetime value
SELECT CONVERT(VARCHAR(20),TimeTransfer,120)
FROM PREMIUM
WHERE strAccountID = ?, $_SESSION['strAccountID']);
Use CONVERT() function
SELECT CONVERT(varchar(20),TimeTransfer,120)
FROM PREMIUM where strAccountID = ?, $_SESSION['strAccountID']);
Note : This gives time in 24 hour format
See this link for Date formats in SQL Server

How to use XML data of SQL table column and perform tasks based on tag values

I need some help. I am suppose to get XML data from column of a table. The XML data has many tags. One of the tag contains values like
<Code date= 30/03/2013>
<apr id =1> -2 </apr>
<rdv id =2> 1 </rdv>
</code>
I need to run a particular task which checks the date. Like if today's date= (Code date -2) or
today's date = (code date + 1)
run a mailer task.
How should I go about it ? Please forgive me for the XML data format. I am naive in XML.
Create 2 variables to store the XML column Date value and other one to get the current date .To write an expression ,select the variable ,right click on it .In the properties windows Set EvaluateAsExpression =true and write the expression
Name DataType Expression
ExecDate DateTime
CurrentDate DateTime GETDATE()
Use Execute SQL Task .Set Resultset to Single Row and write the following code to read the date value from the XML column in your table
SELECT
convert(datetime,XMLData.value('(/Code/#date)[1]', 'varchar(10)'),103) as PkgDate
from yourTable
Demo in SQL Fiddle
In the resultset tab map the output from the above sql query with the variable ExecDate
Result Name Variable Name
PkgDate ExecDate
Put another Task or component Ex SEND Mail TASK after Execute SQL Task and write an expression in the Precedence Constraint.
Expression : #ExecDate==#CurrentDate
Only when the Date value from the XML column matches with the Current Date which is stored in the variable #CurrentDate then only the other components after Execute SQL Task will execute .
today's date= (Code date -2) or today's date = (code date + 1) run a mailer task.
In order to perform the above expression ,you need to change the sql code in Execute SQL Task
To get CodeDate +1
SELECT
Dateadd(day,1,convert(datetime,XMLData.value('(/Code/#date)[1]', 'varchar(10)'),103)) as PkgDate
from yourTable
I don't have the SSIS environment to test it now but this is how you should be doing it

Resources