我有一个工作正常的更新查询,但它太慢了,需要2分钟才能完成。还有其他方法可以编写此查询以加快速度吗?这是我的代码谢谢:
UPDATE #tmpIMDS
SET
ModelFileName = b.ModelFileName,
SendEMail = b.SendEMail
FROM
(
SELECT DISTINCT
IMDSConversionReportData.ModelNumber,
ModelFileName,
'Send Email' AS SendEmail
FROM
IMDSConversionReportData,
(
SELECT DISTINCT
ModelNumber,
Max(DateAdded) AS DateAdded
FROM
IMDSConversionReportData
GROUP BY
ModelNumber) a
WHERE
IMDSConversionReportData.ModelNumber = a.ModelNumber
AND IMDSConversionReportData.DateAdded = a.DateAdded
) b
WHERE ModelID = b.ModelNumber
答案 0 :(得分:2)
您可以生成IMDSConversionReportData
来识别每DateAdded
个ModelNumber
,而不是按row_number
表两次以获得DateAdded
每ModelNumber
}列。
当您只选择一个distinct
无意义的非聚合列时,同时删除group by
试试这个
;WITH cte
AS (SELECT *,
'Send Email' AS SendEmail,
Row_number()OVER(partition BY ModelNumber ORDER BY DateAdded DESC) AS rn
FROM IMDSConversionReportData)
UPDATE t
SET ModelFileName = c.ModelFileName,
SendEMail = c.SendEMail
FROM #tmpIMDS t
INNER JOIN cte c
ON t.ModelID = c.ModelNumber
Where Rn = 1
注意:始终使用正确的INNER JOIN
语法连接两个表而不是旧式逗号分隔连接。我们总是发现INNER Join
语法更强可读。将过滤器单独保留在Where
子句