I am restrained to a legacy database structure and require some stats results. The following query works, but is inefficient and slow ...
SELECT various, other, native, columns,
(SELECT client FROM clients WHERE id = clientid) AS client,
(SELECT name FROM categories WHERE id = (SELECT categoryid FROM clients WHERE id = clientid)) AS category,
(SELECT fullname FROM staff WHERE id = producerid) AS producer,
ISNULL((SELECT SUM(amount) FROM JobsVoiceWork v WHERE v.jobid = j.id),0) AS voicecosts,
(SELECT COUNT(*) FROM Scripts s WHERE s.jobid = j.id) AS numberofscriptscompleted,
ISNULL((SELECT SUM(duration) FROM TimeLog WHERE jobid = j.id),0)/60 AS totaltime,
ISNULL((SELECT SUM(duration) FROM TimeLog WHERE jobid = j.id AND jobeditid = 3 AND jobpart = 'Add'),0)/60 AS PartAdd,
ISNULL((SELECT SUM(duration) FROM TimeLog WHERE jobid = j.id AND jobeditid = 3 AND jobpart = 'Update'),0)/60 AS PartUpdate,
ISNULL((SELECT SUM(duration) FROM TimeLog WHERE jobid = j.id AND jobeditid = 3 AND jobpart = 'Produce'),0)/60 AS PartProduce,
ISNULL((SELECT SUM(duration) FROM TimeLog WHERE jobid = j.id AND jobeditid = 3 AND jobpart = 'Amend'),0)/60 AS PartAmend,
ISNULL((SELECT SUM(duration) FROM TimeLog WHERE jobid = j.id AND jobeditid = 4),0)/60 AS EditProducerError,
ISNULL((SELECT SUM(duration) FROM TimeLog WHERE jobid = j.id AND jobeditid = 8),0)/60 AS EditVoiceError,
ISNULL((SELECT SUM(duration) FROM TimeLog WHERE jobid = j.id AND jobeditid = 1),0)/60 AS EditClientError,
ISNULL((SELECT SUM(duration) FROM TimeLog WHERE jobid = j.id AND jobeditid = 2),0)/60 AS EditEntryError,
ISNULL((SELECT SUM(duration) FROM TimeLog WHERE jobid = j.id AND jobeditid = 5),0)/60 AS EditPronunciation,
ISNULL((SELECT SUM(duration) FROM TimeLog WHERE jobid = j.id AND jobeditid = 6),0)/60 AS EditRemixRequest,
ISNULL((SELECT SUM(duration) FROM TimeLog WHERE jobid = j.id AND jobeditid = 7),0)/60 AS EditRevoiceRequest
FROM Jobs j
I have show a simplified version of the query, but I have included the repetitive sub queries to clearly demonstrate the inefficiency. I have tried various table join scenarios, but I cannot improve performance.
It looks like it should be possible to improve. Is there a way?
(select * from Timelog where jobid = j.id) as jobtlas a first, then your subsequent subqueries select from jobtl instead of TimeLog. That should give you a much smaller dataset to work with on all your subqueries.