所以我需要加入三个表,然后选择一个月的平均星数,我们会说6月,然后每个类别选择所有的业务。到目前为止,我有:
SELECT B1.Name, B2.Category, AVG(R1.Stars) as Average
FROM Business B1
INNER JOIN Reviews R1
ON B1.ID=R1.BusinessID
INNER JOIN BusinessCategories B2
ON B2.BusinessID=R1.BusinessID
WHERE R1.Date >= convert(datetime,'01-6-2011') AND R1.Date <= convert(datetime,'30-6- 2011')
GROUP BY Name, Category
ORDER BY Category, AVG(R1.Stars) DESC
这让我了解每个企业的平均值,但我不知道如何为每个类别选择顶部。
更新:添加我目前所拥有的样本输出以及我正在寻找的内容:
这是我现在得到的:
Victoria Secrets Accessories 5
Francesca's Collections Accessories 5
Saint 22 Accessories 4
Loehmann's Inc Accessories 3
Arcadia Ice Arena Active Life 5
Arizona Sunrays Gymnastics & Dance Center Active Life 5
Blissful Yoga Studio Active Life 5
Corner Archery Active Life 5
Imagination Avenue Active Life 5
Jump Street Active Life 5
Life Time Fitness Active Life 5
但我想要的是:
Victoria Secrets Accessories 5
Arcadia Ice Arena Active Life 5
Video Paradise Adult 5
或者我想更好的是,如果有一个平局,就像一堆活跃的生活类别,我们会回到该类别的所有顶级企业。
答案 0 :(得分:1)
试试这个:
SELECT T1.Name, T1.Category, T1.Average
FROM
(SELECT B1.Name, B2.Category, AVG(R1.Stars) as Average
FROM Business B1
INNER JOIN Reviews R1
ON B1.ID=R1.BusinessID
INNER JOIN BusinessCategories B2
ON B2.BusinessID=R1.BusinessID
WHERE R1.Date >= convert(datetime,'01-6-2011') AND R1.Date <= convert(datetime,'30-6- 2011')
GROUP BY Name, Category
ORDER BY Category, AVG(R1.Stars) DESC) T1
LEFT JOIN (
SELECT B1.Name, B2.Category, AVG(R1.Stars) as Average
FROM Business B1
INNER JOIN Reviews R1
ON B1.ID=R1.BusinessID
INNER JOIN BusinessCategories B2
ON B2.BusinessID=R1.BusinessID
WHERE R1.Date >= convert(datetime,'01-6-2011') AND R1.Date <= convert(datetime,'30-6- 2011')
GROUP BY Name, Category
ORDER BY Category, AVG(R1.Stars) DESC) T2 on T2.Average> T1.Average AND T1.Category= T2.Category
WHERE T2.Name IS NULL
或强>
SELECT Name,Category,Average FROM
(
SELECT ROW_NUMBER() OVER(Partition By Category ORDER BY AVG(R1.Stars) DESC) as RN, B1.Name, B2.Category, AVG(R1.Stars) as Average
FROM Business B1
INNER JOIN Reviews R1
ON B1.ID=R1.BusinessID
INNER JOIN BusinessCategories B2
ON B2.BusinessID=R1.BusinessID
WHERE R1.Date >= convert(datetime,'01-6-2011') AND R1.Date <= convert(datetime,'30-6- 2011')
GROUP BY Name, Category
ORDER BY Category, AVG(R1.Stars) DESC
) T
WHERE RN=1
答案 1 :(得分:0)
使用max(R1.Stars)代替avg(R1.Stars)
答案 2 :(得分:0)
试试这个:
SELECT FIRST(Name) AS BName, Category, MAX(Average) AS TopAverage
FROM (
SELECT B1.Name, B2.Category, AVG(R1.Stars) as Average
FROM Business B1
INNER JOIN Reviews R1
ON B1.ID=R1.BusinessID
INNER JOIN BusinessCategories B2
ON B2.BusinessID=R1.BusinessID
WHERE R1.Date >= convert(datetime,'01-6-2011') AND R1.Date <= convert(datetime,'30-6- 2011')
GROUP BY Name, Category
) q
GROUP BY Category
ORDER BY Category, TopAverage DESC