SQL Server : Histogram of the starts and stops over time - sql

I am trying to get a histogram of the of the starts and stops over time from a subscriber DB, I know what the result should be but I can't make it work.
The code I am trying is:
Unfortunately I get the message
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string.
If I try
It doesn`t work either:
Msg 242, Level 16, State 3, Line 2
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
How can I get over this and get a histogram table?
Thanks in advance

As per your comments, the start_date and stop_date columns having null values. So filter those values and instead of CONVERT please use CAST, because the convert you used cause an error for certain values
Sample:
DECLARE #End_date AS VARCHAR(50) = '2016-05-15';
SELECT YEAR (CAST(#End_date as DATETIME));
SELECT YEAR (CONVERT(DATETIME, #End_date, 104 ));
Note: I manually type the code by seeing your image. Please correct if any typo.
So the below code will work for your expectation:
SELECT theyear, SUM(isstart) as starts, SUM(isstop) as stops
FROM (
SELECT YEAR(CAST([start_date] AS DATETIME)) as theyear, 1 as isstart, 0 as isstop
FROM Subscribers
WHERE [start_date] IS NOT NULL
UNION ALL
SELECT YEAR(CAST(stop_date AS DATETIME)) as theyear, 0 as isstart, 1 as isstop
FROM Subscribers
WHERE stop_date IS NOT NULL
)s
GROUP BY theyear
ORDER BY theyear

Related

Convert string 'yyyy-mm' to date object

In my SQL table, I have a column with just 'yyyy-mm', how can I covert into a Date object and compare if it is older than 2 months from now?
When I try this, CONVERT fails because the [Month] format is just `yyyy-mm' without the day
where DATEDIFF(day,CONVERT(DATE, [Month]),GETDATE()) < 60
I am using SQL Server.
I have tried the answer from the comment
SELECT
COUNT(*) AS aCount
FROM [MyTable]
where [name] != 'abc'
GROUP BY CONVERT(DATE, [Month] + '-01')
But I get error saying
Msg 8152, Level 16, State 2, Line 1
String or binary data would be truncated.

SQl Server Converting to Date fails , DateTime works

I have a table with a varchar(25) column that holds a date value. A typical value is '11/04/2017'.
This query returns 0 rows
select *
from myTable
where isdate(inputDate) = 0
I am trying to find a max on this, using a date sort.
This query returns the expected result
;with gooddates as
(
select
medcomfolder, PatientId, PatientBirthday, InputDate
from
myTable
where
isdate(inputDate) = 1
)
select max(convert(datetime, inputDate))
from gooddates
This query returns an error.
;with gooddates as
(
select
medcomfolder, PatientId, PatientBirthday, InputDate
from
dwhFuData
where
isdate(inputdate) = 1
)
select max(convert(date, inputdate))
from gooddates
This is the returned error
Msg 241, Level 16, State 1, Line 274
Conversion failed when converting date and/or time from character string
The difference between the 2 queries is that the first is converting to a dateTime while the latter is converting to a date.
At this point, I can move forward w/ the dateTime option, but I am left wondering what I am missing.
I have checked that there are no embedded spaces, and all the columns have a len(InputDate) = 10 (there is NO time data included)
I selected distinct values,put them in excel, and did a date function on each row. I was hoping to get a #VALUE on 1 row. All the rows worked.
So there is nothing silly like '02/31/2019' going on.
How can a dateTime conversion pass when a simple date conversion does not?
My guess is that you have values that include a time stamp following the date (based on the fact that isdate() is always zero).
If so, one simple solution would be to use convert(date, left(inputdate, 10)). Another solution uses try_convert():
try_convert(date, inputdate)
To find the offending values:
select inputdate
from dwhFuData
where try_convert(date, inputdate) is null and inputdate is not null;

show data with shipmentdate bigger than today

i am trying to pulling data for all shipments with shipmentdate greater than todays date. However, I cant figure out an easy conversion of the format of the nvarchar, i get a out of range value error when trying to run this:
select *
from dbo.BAS_CT_RAW_ARCHIVE_TBL
where SHIPMENTDATE > GETDATE()
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.
Try:
select *
from dbo.BAS_CT_RAW_ARCHIVE_TBL
where convert(date, SHIPMENTDATE, 103) > GETDATE()
To see how to use convert with non-standard dates see this.
Further consideration: use proper datatypes for columns, i.e. don't store dates as strings, but as date datatype - it will prevent you from having such problems.
according to your data format that got from comment below should work
select * from dbo.BAS_CT_RAW_ARCHIVE_TBL
where CONVERT(date, SHIPMENTDATE, 103) > convert(date, GETDATE())

I'm having date conversion problems with the 3rd column in the script below

Select c1.CDS_Date, c2.CDS_Date, Dateadd(day, -1 , c2.CDS_Date)
from cte as c1 left join
cte as c2
on c1.[Local Patient Identifier] = c2.[Local Patient Identifier] and
c1.JoinKey = c2.JoinKey - 1
Can I get come help please?
I got no issues with c1.CDS_Date and c2.CDS_Date.
I receive the following error message as soon as I include the 3rd column:
(24 rows affected)
Msg 242, Level 16, State 3, Line 50
The conversion of a varchar data type to a datetime data type resulted in an --out-of-range value.
That is because your CDS_Date is not of date/datetime type but is a string.
Here is an example:
declare #t table (CDS_Date varchar(100));
insert into #t values ('28/10/2017');
set language British;
select CDS_Date, dateadd(day, -1, CDS_Date) as dt
from #t;
-------
--CDS_Date dt
--28/10/2017 2017-10-27 00:00:00.000
set language us_english;
select CDS_Date, dateadd(day, -1, CDS_Date) as dt
from #t;
--Msg 242, Level 16, State 3, Line 40
--The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
This example shows you that not every string can be converted to date EVEN IF it seems to you that it represents a valid data. This is because server expects a date that you pass as a string to be in the certain format that depends on session language.
To be independent of session language you shoud pass your date string using convert function and specifying the format of your date.
In my example I can fix the issue converting to date with style 103:
select CDS_Date, dateadd(day, -1, convert(date, CDS_Date, 103)) as dt
from #t;
----
--CDS_Date dt
--28/10/2017 2017-10-27
Now it gives me the correct result in both languages just because it knows that my input strings are of 103 format, i.e. dd/mm/yyyy

trying to get age from date of birth

SELECT [ID_KUNDNR]
,CASE
WHEN DA_FODELSEAR IS NULL THEN 0
WHEN dateadd(year, datediff (year, DA_FODELSEAR, getdate()), DA_FODELSEAR) > getdate() THEN datediff (year, DA_FODELSEAR, getdate()) - 1
ELSE datediff (year, DA_FODELSEAR, getdate())
END As Age
,[Catalog]
FROM Table
I get
Msg 8115, Level 16, State 2, Line 2
Arithmetic overflow error converting
expression to data type datetime.
Any solutions?
I'm just wondering why you are using case. Try the below and see whether it works.
SELECT [ID_KUNDNR] ,
datediff (year, 0, (getdate()-DA_FODELSEAR)) as Age,
Catalog
From Table
But again are you sure all values of DA_FODELSEAR is convertable to datetime?
If you have trouble try this.
SELECT [ID_KUNDNR] ,
Case When ISDATE(DA_FODELSEAR) = 0 Then 0 Else
datediff (year, 0, (getdate()-DA_FODELSEAR))
End as Age,
Catalog
From Table
Incase you want to know, which rows are causing this conversion problem select the table with 'where IsDATE(DA_FODELSEAR) = 0'
You have to make sure that DA_FODELSEAR is in correct datetime format. You can do it by using CAST(DA_FODELSEAR as DATETIME) and check.
I think that your problem lies here dateadd(year, datediff(year, DA_FODELSEAR, getdate()), DA_FODELSEAR). You have a value in your DA_FODELSEAR that is not in a DATETIME format. I would run a SELECT statement to find the offending value. You are checking for NULL but what about a blank space?