7

我有一张满是杂志的桌子,需要提取每本杂志的最新一期。

我试过了

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

它返回不同的杂志,但不返回我需要的其余数据。

更新:

图式

-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

所以我想要返回的结果是:

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

5 回答 5

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 ;
于 2012-07-11T14:17:37.030 回答
9
SELECT id, MAX(onSale) as latest, magazine
FROM product
GROUP BY magazine
ORDER BY latest DESC
于 2012-07-11T14:49:30.607 回答
3

给出的答案都不是正确的,因为它们返回一组不相关的数据,这些数据不代表一个确切的行。id可能与值不在同一idonsale

以下将起作用:

SELECT
    id, onsale, magazine
FROM (
    SELECT
       id, onsale, magazine
    FROM
        product
    ORDER BY
        onsale DESC) AS a
GROUP BY
    magazine
于 2019-08-02T03:55:52.573 回答
2

这看起来像你需要的:

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

在以下位置查看:

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

更新: 我稍微改变了查询,返回 MAX(onsale)

于 2012-07-11T14:38:01.753 回答
-1

您需要将“其余数据”放在第一个选择中:

SELECT DISTINCT magazine, "rest of data"
FROM product p 
INNER JOIN 
( SELECT title, MAX(onSale) AS Latest 
FROM product 
GROUP BY magazine ) groupedp
于 2012-07-11T13:52:37.960 回答