如何获得每个位置的最高评级和产品?这更多的是sql语句。任何人都可以帮助找出错误在哪里?它不会检索我想要的值。
*使用Mysql数据库
这是我的sql语句:
SELECT r.rating,
r.product,
l.places,
l.address,
l.telephone,
l.lng,
l.lat
FROM locations AS l
LEFT JOIN ratings AS r
ON l.places = r.places
ORDER BY r.rating DESC
答案 0 :(得分:2)
因为您还没有提到您正在使用的数据库服务器,所以下面的查询几乎适用于所有RDBMS,包括MySQL
SELECT r.rating,
r.product,
l.places,
l.address,
l.telephone,
l.lng,
l.lat
FROM locations AS l
INNER JOIN ratings AS r
ON l.places = r.places
(
SELECT a.places, b.product, MAX(b.rating) max_rating
FROM locations a
INNER JOIN ratings b
ON a.places = b.places
GROUP BY a.places, b.product
) c ON l.places = c.places AND
r.product = c.product AND
r.rating = c.max_Rating
ORDER BY r.rating desc
<击> 撞击>
<击>如果您的RDBMS支持窗口函数,则
SELECT rating, product, places,
address, telephone, lng, lat
FROM
(
SELECT r.rating, r.product, l.places,
l.address, l.telephone, l.lng, l.lat
ROW_NUMBER() OVER (PARTITION BY r.product, l.places
ORDER BY r.rating DESC) rn
FROM locations AS l
INNER JOIN ratings AS r
ON l.places = r.places
) x
WHERE x.rn = 1
ORDER BY rating desc
击> <击> 撞击>
答案 1 :(得分:1)
假设更高版本的sql-server。这没有经过测试 - 我对正确的分区有点不确定...... l.places
或r.product
。试试这个......
;WITH cte
as
(
SELECT
r.rating,
r.product,
l.places,
l.address,
l.telephone,
l.lng,
l.lat,
[rnk] = RANK OVER(PARTITION BY l.places ORDER BY r.rating DESC)
FROM locations AS l
LEFT JOIN ratings AS r
ON l.places = r.places
)
SELECT
rating,
product,
places,
address,
telephone,
lng,
lat
FROM cte
WHERE [rnk] = 1
ORDER BY rating DESC
答案 2 :(得分:1)
SQL-Server版本(2005及更高版本):
WITH x
AS (SELECT r.rating,
r.product,
l.places,
l.address,
l.telephone,
l.lng,
l.lat,
RN = Rank()
OVER(
partition BY l.places
ORDER BY rating DESC)
FROM locations AS l
INNER JOIN ratings AS r
ON l.places = r.places
SELECT * FROM x WHERE rn = 1