MySql:查找类型中每个产品子类型的最近日期

MySql: Find nearest date for each product subtype within a type

如果之前有人问过这个问题,我深表歉意,但我在 Whosebug 中找不到相同的问题。

我有一个 table 命名价格,像这样,其中 typesubtypedate 是主键:

type subtype      date       price
18  |  DFY  |  2019-06-27  |  230
18  |  DFY  |  2019-06-28  |  241
18  |  RGY  |  2019-06-28  |  234
23  |  NDO  |  2019-06-26  |  227
23  |  NDO  |  2019-06-27  |  241
23  |  SOG  |  2019-06-26  |  235
23  |  SOG  |  2019-06-27  |  239
23  |  SOG  |  2019-06-28  |  292
23  |  SOG  |  2019-06-29  |  238
23  |  SOG  |  2019-07-02  |  236

对于给定的类型,我最多需要为其每个子类型检索一行,其中 date 是最接近给定日期的日期,最多比给定日期早 5 天,但不能晚于给定日期。

例如,对于类型 23 和给定日期 2019-06-30,预期结果是这两行:

23  NDO 2019-06-27  241
23  SOG 2019-06-29  238

我试过这个:

select * from
    (select * from
        (select t.*, datediff('2019-06-30', t.date) as difference
            from prices t
            where t.type = 23
            and t.date < '2019-06-30'
            having difference <= 5
        ) temp
    order by temp.difference
    ) temp2
group by temp2.subtype

然而,返回的两个行并不是差异最小的行。

由于我设计数据访问代码的方式,它必须全部在一个语句中。

架构(MySQL v5.7)

CREATE TABLE my_table (
  `type` INTEGER,
  `subtype` VARCHAR(3),
  `date` date,
  `price` INTEGER,
  PRIMARY KEY(type,subtype,date)
);

INSERT INTO my_table
  (`type`, `subtype`, `date`, `price`)
VALUES
  ('18', 'DFY', '2019-06-27', '230'),
  ('18', 'DFY', '2019-06-28', '241'),
  ('18', 'RGY', '2019-06-28', '234'),
  ('23', 'NDO', '2019-06-26', '227'),
  ('23', 'NDO', '2019-06-27', '241'),
  ('23', 'SOG', '2019-06-26', '235'),
  ('23', 'SOG', '2019-06-27', '239'),
  ('23', 'SOG', '2019-06-28', '292'),
  ('23', 'SOG', '2019-06-29', '238'),
  ('23', 'SOG', '2019-07-02', '236');

查询#1

SELECT a.*
  FROM my_table a
  JOIN
      ( SELECT type
             , subtype
             , MAX(date) date
          FROM my_table
         WHERE date BETWEEN '2019-06-30' - INTERVAL 5 DAY AND '2019-06-30'
         GROUP
            BY type
             , subtype
      ) b
     ON b.type = a.type
    AND b.subtype = a.subtype
    AND b.date = a.date;

| type | subtype | date       | price |
| ---- | ------- | ---------- | ----- |
| 18   | DFY     | 2019-06-28 | 241   |
| 18   | RGY     | 2019-06-28 | 234   |
| 23   | NDO     | 2019-06-27 | 241   |
| 23   | SOG     | 2019-06-29 | 238   |

View on DB Fiddle