【问题标题】:Select latest data per group from joined tables从联接表中选择每组的最新数据
【发布时间】:2015-06-30 10:34:53
【问题描述】:

我有两张这样的表:

survey:
survey_id | store_code | timestamp

product_stock:
survey_id | product_code | production_month | value

如何根据调查时间戳并按 store_code、product_code 和 production_month 分组获得最新值?

例如,如果我有

survey_id | store_code | timestamp
1           store_1      2015-04-20
2           store_1      2015-04-22
3           store_2      2015-04-21
4           store_2      2015-04-22

survey_id | product_code | production_month | value
1           product_1      2                  15
2           product_1      2                  10
1           product_1      3                  20
1           product_2      2                  12
3           product_2      2                  23
4           product_2      2                  17

它会返回这样的结果

survey_id | store_code | time_stamp | product_code | production_month | value
2           store_1      2015-04-22   product_1      2                  10
1           store_1      2015-04-20   product_1      3                  20
1           store_1      2015-04-20   product_2      2                  12
4           store_2      2015-04-22   product_2      2                  17

而且它需要尽可能快,因为数据库的大小相当大

【问题讨论】:

  • “根据调查时间戳获取最新值”是什么意思?我不明白你的这部分问题。
  • 抱歉英语不好,不是母语人士...我的意思是根据调查的时间戳列选择最新的行。
  • 所以你只想选择最新的一行?一行结果?
  • 是的,按 store_code、product_code 和生产月份分组
  • 嗯,最新的基于时间戳列上的日期

标签: mysql greatest-n-per-group


【解决方案1】:

已更新 - 请再次运行查询

这是我的答案:

SELECT survey.survey_id, survey.store_code, survey.timestamp, product_stock.survey_id, product_stock.product_code, product_stock.production_month, product_stock.value 
FROM survey 
INNER JOIN product_stock
ON survey.survey_id = product_stock.survey_id
WHERE survey.timestamp = (SELECT MAX(timestamp) 
               FROM survey)
GROUP BY survey.store_code,product_stock.product_code,product_stock.production_month;

【讨论】:

  • 如果我包含 where 子句,它似乎返回 0 行,如果我把它取出它返回每个组的第一次出现
  • 已更新 - 请再次运行查询。
猜你喜欢
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 2018-02-11
  • 2017-05-22
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多