我有这个:
SELECT Product.ProductID, Product.Name, Product.GroupID, Product.GradeID,
AVG(tblReview.Grade) AS Grade
FROM Product left Join tblReview ON Product.GroupID = tblReview.GroupID
WHERE (Product.CategoryID = @CategoryID)
GROUP BY Product.ProductID, Product.Name, Product.GroupID, Product.GradeID
我想只返回Product.Name唯一的行。如果我创建SELECT DISTINCT
ProductID
每行都不同,那么所有行都是唯一的。
答案 0 :(得分:1)
你可以做这样的事情(见下文),但这假设你不在乎两个同名的产品是否有不同的GroupID等,因为你不能真正列出那些,除非你使用不同的方法(多个查询)。
SELECT Product.Name
, max(Product.ProductID) as ProductID
, max(Product.GroupID) as GroupID
, max(Product.GradeID) as GradeID,
, AVG(tblReview.Grade) AS Grade
FROM Product left Join tblReview ON Product.GroupID = tblReview.GroupID
WHERE (Product.CategoryID = @CategoryID)
GROUP BY Product.Name
HAVING COUNT(distinct Product.Name) = 1
答案 1 :(得分:1)
这对你有用吗?
SELECT Product.ProductID, Product.Name, Product.GroupID, Product.GradeID,
AVG(tblReview.Grade) AS Grade
FROM Product left Join tblReview ON Product.GroupID = tblReview.GroupID
WHERE (Product.CategoryID = @CategoryID)
GROUP BY Product.ProductID, Product.Name, Product.GroupID, Product.GradeID
HAVING COUNT(Product.Name)=1
答案 2 :(得分:0)
SELECT p.ProductID, p.Name, p.GroupID, p.GradeID,
(
SELECT AVG(grade)
FROM tblReview r
WHERE r.GroupID = p.GroupID
) AS Grade
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY productID) AS rna,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY productID DESC) AS rnd
FROM Product
WHERE CategoryID = @CategoryID
) p
WHERE rna = rnd