First, I would suggest capturing the actual execution plan. If you are executing a query from SQL Server Management Studio (SSMS), enable the "Enable actual execution plan" option. If this query is started from another program, start SQL Server Profiler and enable Showplan Statistics Profile and / or Showplan XML Statistics Profile. Browse through this profile and see if the query leads, as you would expect.
Do you have a pointer to ResultTest colm CostId? Only 150 rows, scanning the index in this table is not a big deal. If you do not have an index in this table, you can try it.
I wonder if the execution plan executes nested loops to join the ResultTest. If so, then it will be 150 X 220 million = 33 billion operations. Hashing a join or combining a join will work much better if that is the case. You can force a specific connection to the connection hint OPTION (HASH JOIN) or OPTION (MERGE JOIN) . This in itself can make a huge difference.
The index on #tempAmount has many columns that are not needed for a SELECT query. Also, this is the NONCLUSTERED index. Is there also a CLUSTERED index? If not, you can try converting it to CLUSTERED and get rid of other columns. This will reduce the size of the index and work better, because all rows for id_ script will be contiguous.
source share