使用SubQueries进行SQL查询优化

时间:2016-07-08 18:27:13

标签: sql

有人可以帮我优化/重写此查询吗?我想我已经违反了一些dos而不是这个。

SELECT
    p.PropertyTagNumber, 
    Last_Inv_Hist.Plant, 
    Last_Inv_Hist.Location,
    (
        SELECT     TOP (1) comment_txt
        FROM          Comment
        WHERE      (property_id = p.ID)
        ORDER BY id DESC
    ) AS Remarks

FROM    Property AS p 
LEFT OUTER JOIN
(
    SELECT     i.ID, i.PropertyID,  i.Location, pl.Plant
    FROM InventoryHistory AS i LEFT OUTER JOIN
    Plants AS pl ON i.PlantID = pl.ID
    WHERE   (i.ID = (   SELECT     TOP (1) ID AS max_id
                FROM          InventoryHistory
                WHERE      (PropertyID = i.PropertyID)
                ORDER BY InventoryDate DESC
            )
        )
) AS Last_Inv_Hist 
    ON p.ID = Last_Inv_Hist.PropertyID

1 个答案:

答案 0 :(得分:0)

我将如何做到这一点

WITH inv AS
(
   SELECT ID, PropertyID,  Location, pl.Plant,
          ROW_NUMBER() OVER (PARTITION BY ID ORDER BY InventoryDate DESC) as DateOrder
   FROM InventoryHistory
), MaxInv AS
( SELECT ID, PropertyID,  Location, Plant
  FROM inv 
  WHERE DateOrder = 1
), MaxComment AS
(
  SELECT comment_txt, property_id
  FROM (
    SELECT comment_txt, property_id,
           ROW_NUMBER() OVER (PARTITION BY property_id ORDER BY ID DESC) AS IdOrder
    FROM   Comment
  ) X
  WHERE IdOrder = 1
)
SELECT
  p.PropertyTagNumber, 
  MaxInv.Plant, 
  MaxInv.Location,
  MaxComment.Comment_txt
FROM Property AS p 
LEFT JOIN MaxComment On p.ID = MaxComment.propertyID
LEFT JOIN MaxInv ON ON p.ID = MaxInv.PropertyID

一些注意事项 -

  • 通过在CTE中放置找到给定列的最大值的代码(或者您可以使用子查询,我只是认为CTE更容易阅读)您只需要选择一个 - 在您的您正在为每一行选择一个代码(除非您的产品足够智能以进行优化。)

  • 我向您展示了两种有目的地进行CTE的方法 - 有些方法可能比其他方式更好。

  • 我发现评论选择很奇怪 - 为什么要使用ID来决定要显示哪一个?