1

如何获得每个位置的最高评分和产品?这更多的是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 
4

3 回答 3

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

于 2013-01-22T12:37:52.147 回答
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 
于 2013-01-22T12:45:42.753 回答
1

假设更高版本的sql-server。这未经测试 - 我对正确的分区有点不确定......要么l.placesr.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 
于 2013-01-22T12:41:13.270 回答