Need to convert INT to value I can DIFF against - sql

I'm using the below query where the original convert was written for another table with a different date value. The [YMDRCVD] value is (INT, null). I'm using SQL management studio 14 and receiving an Arithmetic overflow error converting expression to data type datetime error message.
SELECT
Year(CH.[YMDRCVD]) as [Receipt date Year],
Month(CH.[YMDRCVD]) as [Receipt Date Month],
COUNT(*) as [Count of Claims],
AVG(convert(numeric(19,2), DATEDIFF(day, CH.[YMDRCVD], CH.[YMDTRANS]))) as [Average Days from Receipt to Initial Finalized] ,
SUM(
CASE WHEN DATEDIFF(day, CH.[YMDRCVD], CH.[YMDTRANS]) > 10 THEN 1
ELSE 0
END) as [Count Processed in > 10 Days]
FROM [SERVICE_X] CH WITH (NOLOCK)
WHERE
CH.[YMDRCVD] >= '1/1/2016'
AND CH.[YMDRCVD] < '6/1/2016'
AND DATEDIFF(day, CH.[YMDRCVD], CH.[YMDTRANS]) < 20
AND DATEDIFF(day, CH.[YMDRCVD], CH.[YMDTRANS]) >= 0
GROUP BY Year(CH.[YMDRCVD]),
Month(CH.[YMDRCVD])
ORDER BY
Year(CH.[YMDRCVD]),
Month(CH.[YMDRCVD])

You are receiving this error because you are trying to call a date function on a value not of data type date / datetime.
You need to convert [YMDRCVD] to date time.
Check out this post: Convert INT to DATETIME (SQL)

Use the following to decode the date:
For YYYYMMDD:
DATEFROMPARTS( FLOOR([YMDRCVD]/10000), FLOOR([YMDRCVD]/100)%100, [YMDRCVD]%100 )

Related

Snowflake SQL Query - Invalid Argument Function Using DATEADD()

I have the below SQL query I am using in Snowflake where, if the day of the week = Monday, I need to subtract 48 hours from 'HOURS_SINCE_UPDATE':
SELECT DAYNAME(GetDate()) AS DAY,
INC_PUBLIC.INCIDENT_NUMBER,
INC_PUBLIC.COMPANY,
INC_PUBLIC.ASSIGNED_GROUP,
INC_PUBLIC.ASSIGNEE_FULL_NAME,
INC_PUBLIC.ASSIGNEE_ID,
INC_PUBLIC.SUMMARY,
INC_PUBLIC.SUBMIT_DATE_TIME,
INC_PUBLIC.TARGET_DATE_TIME,
INC_PUBLIC.STATUS,
WORK_LOGS.WORK_INFO_TYPE,
WORK_LOGS.SUMMARY,
WORK_LOGS.NOTES,
CASE
WHEN WORK_LOGS.SUBMIT_DATE_TIME IS NULL THEN INC_PUBLIC.SUBMIT_DATE_TIME
ELSE WORK_LOGS.SUBMIT_DATE_TIME
END AS WL_SUBMIT_DATE_TIME,
CASE
WHEN DAY = 'Mon' then DATEADD(HOUR, -48, DATEDIFF(HOURS, WL_SUBMIT_DATE_TIME, GETDATE()))
ELSE DATEDIFF(HOURS, WL_SUBMIT_DATE_TIME, GETDATE())
END AS HOURS_SINCE_UPDATE,
ROW_NUMBER() OVER (PARTITION BY INC_PUBLIC.INCIDENT_NUMBER ORDER BY WORK_LOGS.SUBMIT_DATE_TIME desc) RW,
CASE
WHEN INC_PUBLIC.TARGET_DATE_TIME IS NULL THEN 'Target date is blank'
WHEN TARGET_DATE_TIME < GETDATE() THEN 'Target date expired'
WHEN HOURS_SINCE_UPDATE > 48 THEN 'Overdue for an update'
WHEN INC_PUBLIC.STATUS = 'Assigned' THEN 'Ticket in assigned status'
ELSE 'Good'
END AS REASON_ON_REPORT
FROM SFDW_PROD.SERVICE_MANAGEMENT.INCIDENT_PUBLIC AS INC_PUBLIC
LEFT JOIN
(
SELECT INCIDENT_NUMBER, SUBMIT_DATE_TIME, WORK_INFO_TYPE, SUMMARY, NOTES
FROM SFDW_PROD.SERVICE_MANAGEMENT.INCIDENT_WORK_INFO_PUBLIC
WHERE SUMMARY NOT IN ('Email-Inbound', 'TicketLogger Classification', 'APPMETADATA', 'Auto-Triage Assignment')
AND WORK_INFO_TYPE IN ('Email System', 'Associate Phone Communication','IM Communication','Customer Phone Communication', 'Working Log')
) AS WORK_LOGS
ON INC_PUBLIC.INCIDENT_NUMBER = WORK_LOGS.INCIDENT_NUMBER
WHERE (INC_PUBLIC.ASSIGNED_GROUP LIKE 'DS$_%' ESCAPE '$' AND INC_PUBLIC.STATUS_CODE IN (1,2,3) AND INC_PUBLIC.ASSIGNEE_FULL_NAME != 'NS')
ORDER BY INC_PUBLIC.INCIDENT_NUMBER, WORK_LOGS.SUBMIT_DATE_TIME
limit 100;
CASE
WHEN DAYNAME(GetDate()) = 'Mon' then TIMEADD(HOURS, 48, DATEDIFF(HOUR, WORK_LOGS.SUBMIT_DATE_TIME, GETDATE()))
ELSE DATEDIFF(HOURS, WORK_LOGS.SUBMIT_DATE_TIME, GETDATE())
END AS HOURS_SINCE_UPDATE,
I keep getting the following error:
SQL compilation error: error line 19 at position 30 Invalid argument types for function 'DATE_ADDHOURSTOTIMESTAMP': (NUMBER(2,0), NUMBER(9,0))
What am I doing wrong?
I didn't check the whole query but the error is related to this part:
DATEADD(HOUR, -48, DATEDIFF(HOURS, WL_SUBMIT_DATE_TIME, GETDATE()))
You calculate the time difference (in hours) between WL_SUBMIT_DATE_TIME and the current date. It returns a number, not a date. Then you try to use this number with the DATEADD function, and it expects to have a date instead of a number. This is what you get this error:
If you want to subtract 48 hours, then just subtract it:
DATEDIFF(HOURS, WL_SUBMIT_DATE_TIME, GETDATE()) - 48

Dynamically SELECT a column based on value of row at first of month

The following query:
SELECT Confirmed, Interim, Declared, Date
FROM Interest_Hist
WHERE Date BETWEEN '2019-08-01' AND '2019-12-04'
ORDER BY Date ASC
Returns the following sample data:
Confirmed Interim Declared Date
Y 0.314 0.0788 2019-08-01
0.317 0 2019-08-02
...
0.245 0 2019-08-31
0.222 0.219 2019-09-01
0.198 0 2019-09-02
...
Y 0.50 0.454 2019-12-01
0.51 0 2019-12-02
0.52 0 2019-12-03
0.53 0 2019-12-04
Where on the first of the month, Confirmed = Y, I need to return the Declared column for that month.
Note, Confirmed = Y will only exist on the first of the month. That column is blank in all other cases
Otherwise, I need to return each Interim column for the month.
Thus far, I have been able to return the SUM of either column, but not the individual values.
SELECT
CASE WHEN SUM(CASE WHEN IRc_Confirmed = 'Y' THEN 1 ELSE 0 END) = 0
THEN Interim
ELSE Declared
END AS Rate
FROM Fund_Interest
WHERE Date BETWEEN '2019-08-01' AND '2019-12-04'
GROUP BY
DATEADD(month, DATEDIFF(month, 0, Date), 0), Interim, Declared
ORDER BY
DATEADD(month, DATEDIFF(month, 0, Date), 0)
The expected output given the data at the top is as follows
0.0788
0
...
0
0.222
0.198
...
0.454
0
0
0
Find all the year months where the first day is Y:
SELECT year([date]) as yr, month([date]) as mo
FROM fund_interest
WHERE DAY([date]) = 1 and confirmed = 'Y'
This gives you a list of years and months where there is a Y on the first eg Aug 2019
Now make it a cte and left join it back to your data on year and month, and where the join succeeds return declared else interim:
WITH x AS(
SELECT year([date]) as yr, month([date]) as mo
FROM fund_interest
WHERE DAY([date]) = 1 and confirmed = 'Y'
)
SELECT
CASE WHEN x.yr IS NOT NULL THEN f.declared ELSE f.interim END AS something
FROM
fund_interest f
LEFT OUTER JOIN x ON x.yr = year(f.[date]) AND x.mo = month(f.[date])
All of the rows of different days from Aug 2019 and Dec 2019 will succeed in the join. They will have a NOT NULL yr value and hence the declared will show. For all Sep 2019 rows there is no match in the join (Sep 2019 is not returned by the query in the CTE), yr is null, interim shows instead
For a better idea of what is going on do a SELECT *
If you want to use just a single column the EOMONTH function could be used to return a consistent date every month. Replace MONTH with EOMONTH. Remove calls to YEAR from the query
Do not use reserved words like DATE as column names, by the way
You can use a CTE to group by month and year and then join to your original table (Interest_Hist) on the month and year parts of your date field. You can then select the Interim or Declared value using a simple case statement
;WITH CTE AS
(
SELECT DATEPART(month, DateFld) Mnth, DATEPART(year, DateFld) Yr,
MAX(Confirmed) ConfirmedVal
FROM Interest_Hist
GROUP BY DATEPART(month, DateFld), DATEPART(year, DateFld)
)
SELECT
CASE WHEN c.ConfirmedVal= 'Y' THEN interest.Declared ELSE interest.Interim END
FROM Interest_Hist interest
INNER JOIN CTE c ON
DATEPART(month, interest.DateFld) = c.Mnth AND
DATEPART(year, interest.DateFld) = c.Yr
You can see the query in action here
This took me way longer than it probably should have.
SELECT IIF( MAX(Confirmed) OVER(PARTITION BY CONVERT(VARCHAR(6), Date, 112)) = 'Y', Declared, Interim) Interest_Rate
FROM Interest_Hist
WHERE DateBETWEEN '01-AUG-2019' AND '04-DEC-2019'
ORDER BY Date

Error constructing Date

I can't understand why this is giving me the error "Cannot construct data type date, some of the arguments have values which are not valid."
This is my query:
SELECT TOP 1 pc.Comment AS [Comment], pc.[Month] AS [Month], pc.[Year] AS [Year]
FROM PECCS.dbo.ProjectComment pc
WHERE pc.ProjectId = 11501 AND
pc.Type = 'OYEO' AND
(DATEFROMPARTS(pc.[Year], pc.[Month], 1) <= DATEFROMPARTS(2017, 12, 1)) AND
pc.ResourceCategoryID = 1
ORDER BY pc.[Year] DESC, pc.[Month] DESC
The parameters that I am passing are valid. What I believe is the problem is that there are records in the table where Month = 0. I believe that's causing the problem here: (DATEFROMPARTS(pc.[Year], pc.[Month], 1)
Is [Month] an INT column in your database, or a VARCHAR with the name of the month spelled out? Using similar columns to test this, it gives me the same error, until I changed [Month] to a different column [Month of Year], which is INT. Then it works fine.
I solved the issue by converting those months where it is 0 to a default Month value. In this case, I chose 12:
SELECT TOP 1 pc.Comment AS [Comment], pc.[Month] AS [Month], pc.[Year] AS [Year]
FROM PECCS.dbo.ProjectComment pc
WHERE pc.ProjectId = 11501 AND
pc.Type = 'OYEO' AND
(DATEFROMPARTS(pc.Year, CASE WHEN pc.[Month] = 0 THEN 12 ELSE pc.[Month] END, 1) <= DATEFROMPARTS(#Year, #Month, 1)) AND
pc.ResourceCategoryID = 1
ORDER BY pc.[Year] DESC, pc.[Month] DESC

I need to use DATEDIFF to get the difference in minutes between the start and finish of a route patrol

I'm trying to create a view that contains 2 coloumns, a PatrolID, and a numeric value representing the length of a patrol (in minutes). The patrol is marked as started in a TYPE coloumn with the variables PATROL_STARTED and PATROL_FINISHED. The time of these is clocked in a OCCURRENCE DATE coloumn with a timestamp (datetime).
I have attempted the following but it doesn't seem to want to work:
CREATE VIEW RouteDurations AS
SELECT PatrolID,
DATEDIFF(mi, MAX(CASE WHEN ACTION="PATROL_FINISH" THEN [Occurrence Date] END),
MIN(CASE WHEN ACTION="PATROL_START" THEN [Occurrence Date] END)
) AS Duration
FROM [Data Import] AS t
GROUP BY PatrolID
I cant for the life of me work out why not. Anyone pick anything up?
SQL Server doesn't use double quotes for strings. Try this:
SELECT PatrolID,
DATEDIFF(minute,
MIN(CASE WHEN ACTION = 'PATROL_STARTED' THEN [Occurrence Date] END),
MAX(CASE WHEN ACTION = 'PATROL_FINISHED' THEN [Occurrence Date] END)
) AS Duration
FROM [Data Import] AS t
GROUP BY PatrolID;
In addition, the arguments to datediff() is first the start date and then the end date.
You probably want to do a self join. Something like this:
select p1.patrolID,
datediff(mi, p1.[Occurrence Date], p2.[Occurrence Date]) minutes
from [Data Import] p1 join [Data Import] p2
on p1.patrolID = p2.patrolID
and p1.action = 'PATROL_START'
and p2.action = 'PATROL_FINISH'
where p1.patrolID = something

Arithmetic overflow error converting expression to data type datetime [SQL SERVER 2008 R2]

I have this query below and I keep getting an error
Arithmetic overflow error converting expression to data type datetime error
when executing. I am pretty sure it has to do with DATE_ID = etc etc, because every time I put in a timestamp in their it works. Can anyone help me ?
SELECT
Dimension.[Every 10 minutes],
COUNT(*) as [Number of Transactions],
df.[Function Name]
FROM
dbo.table, Dimension, DimensionFunction df
WHERE
DATE_ID = DATEADD(day, -1, convert(varchar(50), GETDATE(),20))
AND dbo.table.TIME = Dimension.Time
AND df.FUNCTION_CODE = dbo.table.FUNCTION_CODE
AND INTERFACE_ID = 2
AND dbo.table.FUNCTION_CODE in ('ABX', 'BBB','DDD','EEE')
AND TABLE.TIME BETWEEN '07:00' and '17:59'
GROUP BY
Dimension.[Every 10 minutes], df.[Function Name]
ORDER BY
Dimension.[Every 130 minutes], df.[Function Name]