MySQL finding the most expensive in each zip code

隐身守侯 提交于 2019-12-20 03:18:37

问题


I have a table called Products with the schema (name, city, state, zip_code price).

And I want to find the most expensive products' name for a given state's each zip_code.

I wrote

SELECT zip_code, MAX(price)
FROM products
WHERE products.state = 'NJ'
GROUP BY zip_code

as a subquery, but I couldn't figure out displaying product name and price per zip_code in 'NJ'

I would appreciate if you can help me, Thanks.


回答1:


SELECT
      t.name, t.city, t.zip_code, t.price
FROM  
       ( SELECT zip_code
              , MAX(price) as price 
         FROM products 
         WHERE state = 'NJ' 
         GROUP BY zip_code
       ) AS tm 
    JOIN
        products as t
            ON  tm.zip_code = t.zip_code 
            AND tm.price = t.price
WHERE 
        t.state = 'NJ' 



回答2:


This should work, though I can't vouch for it's efficiency. Per comment, here's an update that pulls back all records with price equal to the max price per zip code.

SELECT *
  FROM products p1
 WHERE p1.state = 'NJ'
   AND p1.price = (select max(price) from products p2
                   where p1.zip_code = p2.zip_code)

http://www.sqlfiddle.com/#!2/98f6d/2




回答3:


Something like this:

SELECT name,price,zip_code
FROM products
WHERE state='NJ' AND price=(SELECT MAX(price) FROM products)



回答4:


I think that you will (either way) need a composite index on products.state,products.zip_code.

Try the following:

SELECT p.zip_code, MAX(p.price) AS max_price, 
(
  SELECT GROUP_CONCAT(CAST(products.id AS CHAR)) FROM products 
  WHERE products.state = 'NJ' AND 
  products.zip_code = p.zip_code AND products.price = MAX(p.price) 
) AS product_ids
FROM products p WHERE p.state = 'NJ' GROUP BY p.zip_code ORDER BY NULL

Note:
GROUP_CONCAT has a limitation regarding the maximum length of the resulting string, see http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_group_concat_max_len . If you are missing some IDs, this could be the reason.



来源:https://stackoverflow.com/questions/9982039/mysql-finding-the-most-expensive-in-each-zip-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!