Mysql查询with group by和having子句

时间:2016-10-07 07:24:29

标签: mysql sql group-by having

我正在构建查询以获得同一产品的最高价格。 我有桌子

-----------------------------------------
|   prod_id  |   price   |    user_id   |
-----------------------------------------
|     4      |   25      |       1      |
|     4      |   38      |       2      |
|     4      |   41      |       3      |
|     7      |   100     |       1      |
|     7      |   95      |       2      |
-----------------------------------------

我想获得以下输出:

-----------------------------------------
|     4      |   41      |       3      |
-----------------------------------------
|     7      |   100     |       1      |
-----------------------------------------

我构建了以下查询,这是不对的。

select * from user_bid group by prod_id having max(price);

有人可以指导我获取所需结果的查询。

4 个答案:

答案 0 :(得分:3)

以下是使用联接的选项:

SELECT p1.*
FROM prod_id
INNER JOIN
(
    SELECT prod_id, MAX(price) AS price    -- this inner subquery finds the maximum
    FROM user_bid                          -- price for each product group
    GROUP BY prod_id
) p2
    ON p1.prod_id = p2.prod_id AND         -- and this join condition retains
       p1.price   = p2.price               -- only records which have this maximum
                                           -- price for each product group

这是一个使用子查询的选项:

SELECT p1.*
FROM prod_id p1
WHERE price = (SELECT MAX(p2.price) FROM prod_id p2 WHERE p1.prod_id = p2.prod_id)

答案 1 :(得分:3)

SELECT *
FROM user_bid 
WHERE (prodid, price) IN
(
    SELECT prodid, MAX(price)
    FROM user_bid 
    GROUP BY prod_id
)

答案 2 :(得分:1)

对于SQL Server

;WITH cte AS

(
SELECT prod_id,price,user_id,
       ROW_NUMBER() OVER(PARTITION BY prod_id ORDER BY price desc) as rank
FROM table Name
)

SELECT prod_id,price,user_id
FROM cte
WHERE rank=1

答案 3 :(得分:0)

使用以下查询:

 $('a#stpa_announcement_details_open').fancybox({
   'afterClose': function() {
                               alert('test') 
                             }
  });

输出:

Image