试图通过CTE找到最小的价值

时间:2017-05-19 18:53:17

标签: sql tsql group-by common-table-expression

我需要找到最便宜的值,然后检索有关此值的信息。我试图通过使用CTE检索chepest项目然后INNER JOIN来检索项目信息,但我得到3条记录而不是单条记录。我怎样才能获得单一记录?

  ;WITH GroupedData AS (
SELECT c.SparePartId, MIN(c.Price) AS MinPrice FROM Catalogue c
    WHERE c.SparePartId  = @SparePartId
    GROUP BY c.SparePartId
    )
  SELECT DISTINCT sp.Id, gd.MinPrice, sp.Name, Image
  FROM SpareParts sp
  INNER JOIN Photos p ON sp.Id = p.SparePartId
  INNER JOIN GroupedData gd ON sp.Id = gd.SparePartId

enter image description here

1 个答案:

答案 0 :(得分:0)

由于您的CTE组和您的WHERE要求结果为单个记录:

SELECT c.SparePartId, MIN(c.Price) AS MinPrice FROM Catalogue c
WHERE c.SparePartId  = @SparePartId
GROUP BY c.SparePartId

由于您sparepart表中的每个spareparts都不太可能有多条记录。然后INNER JOIN到photos必须导致记录膨胀,这意味着对于@SparePArtID,您必须有三个Photos记录。