Convert date time format and select distinct in SQL - sql

I need to select the distinct date time from 2 columns.
First convert the date time into new format 'yyyy-mm-dd hh:mm:ss' and select only the distinct value. Such as: convert and take the only 1 time value 12:59:43 among 3 results.
But when i try to add format or convert function into this, it was failed or not showing right results. Any help please? Thank you.
The original code i use below:
SELECT DISTINCT *
FROM
( SELECT TOP 100000000
[Start] AS Station_Start_Date,
[End] AS Station_End_Date
FROM ***
WHERE *** = 1476541 AND [End] IS NOT NULL AND [Start] IS NOT NULL
GROUP BY
[End],
[Start]
ORDER BY [Start] DESC)

try the following:
SELECT DISTINCT convert(varchar(19), t.Station_Start_Date, 120) Station_Start_Date
, convert(varchar(19), t.Station_End_Date, 120) Station_End_Date
FROM #t t
or
SELECT convert(varchar(19), t.Station_Start_Date, 120) Station_Start_Date
, convert(varchar(19), t.Station_End_Date, 120) Station_End_Date
FROM #t t
GROUP BY convert(varchar(19), t.Station_Start_Date, 120), convert(varchar(19), t.Station_End_Date, 120)
Please find the db<>fiddle here.

Related

T- SQL compare two date column and find month number

I am new in this business. hope you could help me to sort out below problem with CASE Statement. I need to compare two columns where date values are there but the result will be as like as the picture below.
Thank you
Nayeem
Try something like this...
select
first_date
,second_date
,case
when first_date > second_date
then
substring(datename(month,first_date),1,3) + '-' + substring(datename(year,first_date),3,2)
else
substring(datename(month,second_date),1,3) + '-' + substring(datename(year,second_date),3,2)
end as result
from (
select CONVERT(datetime, '2017-08-25') as first_date ,CONVERT(datetime, '2017-02-02') as second_date
union
select CONVERT(datetime, '2018-01-25') as first_date ,CONVERT(datetime, '2018-12-04') as second_date
union
select CONVERT(datetime, '2019-11-14') as first_date ,CONVERT(datetime, '2019-11-14') as second_date
) x;
;
Assuming your date columns are indeed dates, you seem to be looking for:
select format(coalesce(start_date_1, start_date_2), 'MMM-yy')
from t;

Convert nvarchar to date and Get data between two date

I'm collecting data between two date 01/12/2014 and 31/12/2014 but my sql data type in nvarchar
is my query right?
SELECT * from customer where date >= convert(datetime, '01/12/2014', 105)
AND date <= convert(datetime, '31/12/2014', 105)
Result
Msg 242, Level 16, State 3, Line 1
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
can any one solve this problem...
as I know you must separate different parts of a DATE with "-" not with "/" in format 105. here is an example:
SELECT convert(datetime, '23-10-2016', 105) -- dd-mm-yyyy
so you must rewrite your code as:
SELECT * from customer where date >= convert(datetime, '01-12-2014', 105)
AND date <= convert(datetime, '31-12-2014', 105)
The format your string are in, 'dd/mm/yyyy' is 103, not 105 (which is 'dd-mm-yyyy'). So, simply use the correct format:
SELECT *
FROM customer
WHERE [date] >= CONVERT(datetime, '01/12/2014', 103)
AND [date] <= CONVERT(datetime, '31/12/2014', 103)
If your date type is nvarchar why don't you try like this:
SELECT * FROM customer
WHERE date >= '01/12/2014'
AND date <= '31/12/2014'
Do we really need to convert?
SELECT * FROM DBO.CUSTOMER
WHERE CAST([date] AS DATE) >= '01/12/2014' AND
CAST([date] AS DATE) <= '31/12/2014'
I suggest you to use this:
(I think converting to varchar is make more sense)
SELECT *
FROM customer
WHERE CONVERT(varchar, [date], 103) BETWEEN '01/12/2014' AND '31/12/2014'
In Date and Time Styles; 103 is for with British/French standard with century (yyyy) like this dd/mm/yyyy.

Sort a varchar converted datetime column

I have a datetime column, dates are shown like "11/13/2012 1:48:27 PM" I need to convert it to "11/13/12".
I know I can convert it using
convert(varchar(10), datevalue, 1)
but when I sort the column after converting it's not sorting by date. I'm not sure if convert(datetime, datevalue, 1) is supposed to do anything but nothing happenend and I still got the default date value.
I tried this
select convert(varchar(10), datevalue, 1)
from table
order by convert(datetime, datevalue, 1) desc
It works but my bigger query selects distinct and I'm getting an error
ORDER BY items must appear in the select list if SELECT DISTINCT is specified
Try something like:
SELECT CONVERT(varchar(10), datevalue, 1)
FROM table
ORDER BY datevalue desc
Try this:
SELECT CONVERT(DATETIME, datevalue, 103)
FROM table
ORDER BY CONVERT(DATETIME, datevalue, 103)
select convert(varchar(10), datevalue, 1)
from table
order by datevalue desc
You don't need to convert date in order by statement. Only column name would work if its datatype is 'datetime'

Date Time conversion/ Date diff in SSRS

I have an SSRS report where I am using below query.
(This query works fine in SQL server, problem is only in SSRS report)
--DECLARE #Range Number = 10;
SELECT * FROM TBL1 WHERE
USERNAME = 'MIKE'
AND
(
#Range = '10'
and
Convert(datetime, MyDate, 120) <= GETDATE()
)
or
(
#Range IN ('20','30')
and
DATEDIFF(DD, Convert(datetime, MyDate, 120) , GETDATE()) <= #Range
)
Unfortunately the myDate Column coming from database is a varchar column.
The SSRS throws an out-of-range exception.
Then I tried converting Getdate to Convert(varchar(10), getdate(), 120) and compare with myDate (without conversion as myDate is already in YYYY-MM-DD format but as a varchar in database)it still throws error. I assume this time coz SSRS is not able to process datediff in varchar columns.
When I run these queries individually, it works fine. i.e -
Declare #Range Number = 10;
Select * from tbl1
where username = 'MIKE' and
(
#Range = '10'
and
convert(datetime, MyDate, 120) <= getdate()
Has anyone faced similar issue in SSRS ???
Try this!
SELECT * FROM TBL1 WHERE
USERNAME = 'MIKE'
AND
(
#Range = '10'
and
cast(myDate as datetime) <= GETDATE()
)
or
(
#Range IN ('20','30')
and
cast(myDate as datetime) , GETDATE()) <= #Range
)
Presumably, your problem is that some values of myDate are not in the correct format. If you are using a more recent version of SQL Server, the function try_convert() can be a big help.
The reason it is failing is because of your logic. The second condition after the or is looking at all records, not just Mike's. I think you intend for the where clause to be:
SELECT *
FROM TBL1 WHERE
WHERE USERNAME = 'MIKE' AND
((#Range = '10' and Convert(datetime, MyDate, 120) <= GETDATE()
) or
(#Range IN ('20','30') and
DATEDIFF(DD, Convert(datetime, MyDate, 120) , GETDATE()) <= #Range
)
);
Note the extra set of parentheses. Now, this will probably help for this particular query for MIKE. But it won't help overall. Finding the value(s) that fail conversion can be daunting. If you are lucky, they fail easily. You can look for them with starting with:
select MyDate
from tbl1
where MyDate not like '[0-9][0-9][0-9][0-9]-[0-2][0-9]-[0-3][0-9]%';
If you are lucky, then this will find the offending values. Otherwise, you'll have to dive more deeply into the date formats, looking at the particular month and day (and potentially hour, minute, and second) values.
Moral: Store dates as dates. Don't store them as varchar().

How to build this sql query

i want to find the records in sql
from say 25-08-2012 to 01-09-2012
and i want to group by date
here is my query
SELECT CONVERT(VARCHAR(10), date, 105) AS dt,
COUNT(id) AS cnt
FROM tablename
WHERE date BETWEEN CONVERT(DATETIME, '21-08-2012 00:00:00:000',103)
AND CONVERT(DATETIME, '01-09-2012 23:59:00:000' ,103)
GROUP BY CONVERT(VARCHAR(10), date, 105)
i am getting result as
dt cnt
01-09-2012 48
27-08-2012 1
28-08-2012 3
29-08-2012 11
30-08-2012 3
but expect it as
dt cnt
25-08-2012 0
26-08-2012 0
01-09-2012 48
27-08-2012 1
28-08-2012 3
29-08-2012 11
30-08-2012 3
How i can modify above query
i also tried with CASE but no luck
Many Thanks..
The reason you are missing these dates in result is that there's no data for them in your table, however, the following would insure you are getting all of the dates in specified range:
CREATE TABLE #tmp_dates ([date] datetime)
DECLARE #dt_start datetime, #dt_end datetime, #dt_dif int
SET #dt_start = CONVERT(DATETIME, '21-08-2012 00:00:00:000',103)
SET #dt_end = CONVERT(DATETIME, '01-09-2012 23:59:00:000' ,103)
SET #dt_dif = datediff(day,#dt_start,#dt_end)
WHILE #dt_dif >= 0 BEGIN
INSERT INTO #tmp_dates
SELECT dateadd(day,#dt_dif,#dt_start)
SET #dt_dif = #dt_dif - 1
END
SELECT CONVERT(VARCHAR(10), t2.[date], 101) AS dt, COUNT(t1.id) AS cnt
INTO #tmp_result
FROM tablename t1
RIGHT OUTER JOIN #tmp_dates t2
ON CONVERT(VARCHAR(10), t1.[date], 101) = CONVERT(VARCHAR(10), t2.[date], 101)
GROUP BY CONVERT(VARCHAR(10), t2.[date], 101)
ORDER BY CONVERT(DATETIME,CONVERT(VARCHAR(10), t2.[date], 101)) ASC /* DESC */
SELECT convert(VARCHAR(10),CONVERT(DATETIME,dt),105) as dt,cnt FROM #tmp_result
DROP TABLE #tmp_dates
DROP TABLE #tmp_result
Your query cannot be directly modified to return the data you want. To count the dates in question, there must be records in the target table actually having those dates; in your case, however, the dates are merely parameters in the query. As a result, there is no way to incorporate them into your result set.
You must create a secondary table that includes all the dates for which you want data, and then recharacterize your query as a left outer join from that date table to your target table. This will, in turn, give you the zero counts for the dates present in the "date" table, but absent from the target table.
How about using IsNull()? Let me know if this works.
SELECT CONVERT(VARCHAR(10), date, 105) AS dt,
ISNULL(COUNT(id),0) AS cnt
FROM tablename
WHERE date BETWEEN CONVERT(DATETIME, '21-08-2012 00:00:00:000',103)
AND CONVERT(DATETIME, '01-09-2012 23:59:00:000' ,103)
GROUP BY CONVERT(VARCHAR(10), date, 105)