Right now I have this SQL query which is valid but always times out:
SELECT
(
SELECT (MAX(WP_ODOMETER) - MIN(WP_ODOMETER)) / DATEDIFF(DAY, MIN(WP_DATETIME), MAX(WP_DATETIME))
FROM WAYPOINTS
WHERE WP_DATETIME BETWEEN DATEADD(DAY,-14,GETDATE()) AND GETDATE()
AND WP_VTDID = 'L088'
)
AS MAXD,
(
SELECT MAX(WP_ODOMETER)
FROM WAYPOINTS
WHERE WP_DATETIME BETWEEN DATEADD(DAY,-14,GETDATE()) AND GETDATE()
AND WP_VTDID = 'L088'
)
AS MD
I want to create a view based on the above SQL query. Something like this:
SELECT L_VTDID
(
SELECT (MAX(WP_ODOMETER) - MIN(WP_ODOMETER)) / DATEDIFF(DAY, MIN(WP_DATETIME), MAX(WP_DATETIME))
FROM WAYPOINTS
WHERE WP_DATETIME BETWEEN DATEADD(DAY,-14,GETDATE()) AND GETDATE()
AND WP_VTDID = LOCOMOTIVES.L_VTDID
)
AS MAXD,
(
SELECT MAX(WP_ODOMETER)
FROM WAYPOINTS
WHERE WP_DATETIME BETWEEN DATEADD(DAY,-14,GETDATE()) AND GETDATE()
AND WP_VTDID = LOCOMOTIVES.L_VTDID
)
AS MD
FROM LOCOMOTIVES
Since they have the same where clause, you could combine them:
An index on WP_VTDID, WP_DATETIME can speed this up. You could also include WP_ODOMETER in the index, to save the bookmark lookup from the index to the table itself.
If the timeout occurs because someone else is locking the table, try to change the from statement to:
If the query runs fine with NOLOCK, another process is using the table and preventing your query from locking rows.