1

我有一个类似于这样的数据集:

id   product_id   size       color     price   created_date
------------------------------------------------------------------
1    24           small      black     9.99    2012-06-21 00:00:00
2    24           small      red       9.99    2012-06-23 00:00:00
3    24           medium     black     11.99   2012-06-24 00:00:00
4    24           medium     red       11.99   2012-06-24 00:00:00
5    24           large      black     12.99   2012-06-25 00:00:00
6    24           large      red       12.99   2012-06-26 00:00:00
7    24           small      black     8.99    2012-06-27 00:00:00
8    24           medium     black     10.99   2012-06-29 00:00:00
9    24           large      red       13.99   2012-06-30 00:00:00
10   24           medium     red       10.99   2012-07-01 00:00:00

我的预期结果集是:

id   product_id   size       color     price   created_date
------------------------------------------------------------------
2    24           small      red       9.99    2012-06-23 00:00:00
5    24           large      black     12.99   2012-06-25 00:00:00
7    24           small      black     8.99    2012-06-27 00:00:00
8    24           medium     black     10.99   2012-06-29 00:00:00
9    24           large      red       13.99   2012-06-30 00:00:00
10   24           medium     red       10.99   2012-07-01 00:00:00

因此,换句话说,从表中选择所有 product_id = 24 和 size/color 是唯一的,并且只返回 created_date 的最新条目。

我不确定解决这个问题的最佳方法是什么。通过临时表进行子选择?内部联接?某种独特/独特的组合?我可能让这变得比它必须的更困难。

4

1 回答 1

2

您需要获得分组最大值

SELECT   mytable.*
FROM     mytable NATURAL JOIN (
  SELECT   size, color, MAX(created_date) AS created_date
  FROM     mytable
  GROUP BY size, color
) AS t

sqlfiddle上查看。

于 2012-06-29T21:55:21.893 回答