使用MAX()和VALUES()优化SQL语句

时间:2019-01-10 12:32:15

标签: sql sql-server sql-server-2008-r2 left-join

在以下情况下,目标是返回股票的最高评级:

SELECT DISTINCT sd.ShareId
  , CASE 
      WHEN sd.GV01 IS NOT NULL OR sd.GV02 IS NOT NULL OR sd.GV03 IS NOT NULL THEN (
         SELECT MAX(val)
         FROM (VALUES (rmatMG.RankingId), (rmatSG.RankingId), (rmatFG.RankingId)) AS value(val)
         WHERE val IS NOT NULL
    ) 
  END AS minRating
  , sd.TradeValue
FROM dbo.MasterData sd
LEFT JOIN dbo.CfgRatingMatching rmMG ON sd.GV01 = rmMG.RatingIdOne 
LEFT JOIN dbo.CfgRatingmatrix rmatMG ON rmMG.RatingIdCollMatrix = rmatMG.RankingId
LEFT JOIN dbo.CfgRatingMatching rmSG ON sd.GV02 = rmSG.RatingIdTwo 
LEFT JOIN dbo.CfgRatingmatrix rmatSG ON rmSG.RatingIdCollMatrix = rmatSG.RankingId
LEFT JOIN dbo.CfgRatingMatching rmFG ON sd.GV03 = rmFG.RatingIdThree 
LEFT JOIN dbo.CfgRatingmatrix rmatFG ON rmFG.RatingIdCollMatrix = rmatFG.RankingId

有人知道如何优化代码吗?我有很多数据,返回列表几乎要花一分钟多的时间。需要太长时间。

0 个答案:

没有答案