Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select DISTINCT by highest value

Tags:

mysql

I have a table full of magazines, and need to extract the latest unique issue of each magazine.

Ive tried

    SELECT DISTINCT
    magazine
        FROM
    product p
        INNER JOIN
    (SELECT 
        title, MAX(onSale) AS Latest
    FROM
        product
    GROUP BY magazine) groupedp

Which returns the distinct magazines , but not the rest of the data I require.

UPDATE:

schema

-id----onsale----magazine
  1    1/12/12   Fishing Mag
  2    1/11/12   Fishing Mag
  3    12/03/11  Pencil Sharpening Monthly
  4    1/02/10   Pencil Sharpening Monthly
  5    16/04/09  Homes in the Sky

So the result I would like returned would be:

 -id----onsale----magazine
   1    1/12/12   Fishing Mag         
   3    12/03/11  Pencil Sharpening Monthly         
   5    16/04/09  Homes in the Sky
like image 978
BobFlemming Avatar asked Jul 11 '12 13:07

BobFlemming


People also ask

Can we use distinct and Max in SQL?

How to implement MAX(distinct…) in MySQL and what is the difference without using DISTINCT? select max( yourColumnName) from yourTableName; NOTE − Both the above queries give the same result with or without a DISTINCT keyword. MySQL internally converts MAX(yourColumnName) to DISTINCT keyword.

How do you find the maximum value in a column in MySQL?

The MySQL Solution If you're working with MySQL, you can combine MAX() with the GREATEST() function to get the biggest value from two or more fields. Here's the syntax for GREATEST: GREATEST(value1,value2,...) Given two or more arguments, it returns the largest (maximum-valued) argument.

Can you write a SQL query to find the biggest number which only appears once?

Solution. Use select max(num) to select the biggest number. To select the biggest number that only appears once, use having count(num) = 1 as a condition.

How do I find the greatest number in SQL?

SQL MIN() and MAX() Functions The MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.


1 Answers

SELECT 
    p.*
FROM
        product p
    INNER JOIN
        ( SELECT 
              magazine, MAX(onSale) AS latest
          FROM
              product
          GROUP BY 
              magazine
        ) AS groupedp
      ON  groupedp.magazine = p.magazine
      AND groupedp.latest = p.onSale ;
like image 199
ypercubeᵀᴹ Avatar answered Sep 21 '22 15:09

ypercubeᵀᴹ