8

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
BobFlemming
  • 2,040
  • 11
  • 43
  • 59

5 Answers5

12
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 ;
ypercubeᵀᴹ
  • 113,259
  • 19
  • 174
  • 235
10
SELECT id, MAX(onSale) as latest, magazine
FROM product
GROUP BY magazine
ORDER BY latest DESC
Jeff
  • 908
  • 2
  • 9
  • 23
  • 1
    This may show `id` and `onSale` that don't actually match in the table. – ypercubeᵀᴹ Jul 11 '12 at 15:01
  • 1
    @ypercube is correct. Do you need id for anything? Since it is not being aggregated or included in the GROUP BY clause, it can give you inconsistent results – Jeff Jul 11 '12 at 15:07
  • @ypercube Jeff You are both right. The results are incorrect , as the id and onSale do not relate to the same . – BobFlemming Jul 12 '12 at 11:21
  • I downvoted because you need to add a comment that points out that the id and onSale might not match in the results, I will remove my downvote. – Dave Scotese Apr 07 '16 at 17:13
3

None of the given answers are correct, as they return an disassociated set of data that does not represent one exact row. The id may not be the id from the same row as the onsale value.

The following will work:

SELECT
    id, onsale, magazine
FROM (
    SELECT
       id, onsale, magazine
    FROM
        product
    ORDER BY
        onsale DESC) AS a
GROUP BY
    magazine
Dan
  • 473
  • 3
  • 7
2

This looks like what you need:

SELECT id, MAX(onsale) AS onsale, magazine FROM magazines GROUP BY magazine ORDER BY onsale DESC;

Check it out at:

http://sqlfiddle.com/#!2/38e78/3

UPDATE: I've changed query a little, to return MAX(onsale)

Zagor23
  • 1,953
  • 12
  • 14
-1

You need to put the 'rest of data' in the first select:

SELECT DISTINCT magazine, "rest of data"
FROM product p 
INNER JOIN 
( SELECT title, MAX(onSale) AS Latest 
FROM product 
GROUP BY magazine ) groupedp
Iwo Kucharski
  • 3,735
  • 3
  • 50
  • 66
squiter
  • 5,711
  • 4
  • 24
  • 24