我需要找到最便宜的值,然后检索有关此值的信息。我试图通过使用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
答案 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
记录。