SQL-使用DISTINCT或GROUP BY为每个值获取多次出现

时间:2019-02-22 09:39:56

标签: mysql sql

使用DISTINCT或GROUP BY记录每个值(或一组值)的记录,就像在下面的查询中一样:

SELECT id, MAX(price) FROM Products GROUP BY id

结果将类似于:

ID | price
1    10
2    11

每个ID是否有3个不同的价格?

4 个答案:

答案 0 :(得分:1)

如果要获取所有值,可以使用GROUP_CONCAT,例如:

SELECT id, GROUP_CONCAT(price)
FROM table
GROUP BY id;

答案 1 :(得分:1)

如果您的MySql版本支持Window函数,则可以使用RANK()和PARTITION

SELECT id, price
FROM (SELECT id, price, RANK() OVER w as price_rank
      FROM test
      WINDOW w as (PARTITION BY id ORDER BY price desc)) r
WHERE price_rank <= 3 
ORDER BY id, price desc

答案 2 :(得分:1)

您可以在下面尝试-使用自我加入

DEMO

SELECT Products.id, Products.price,COUNT(p.price) AS rank
FROM Products 
LEFT JOIN Products AS p ON Products.id = p.id AND Products.price< p.price
GROUP BY Products.id, Products.price
HAVING COUNT(p.price) < 3
ORDER BY Products.id, Products.price DESC

答案 3 :(得分:0)

获得三个最高价格的一种方法是使用group_concat()substring_index()

SELECT id,
       SUBSTRING_INDEX(GROUP_CONCAT(price ORDER BY price DESC), ',' 3) as top3_prices
FROM Products
GROUP BY id;