【问题标题】:Query table with multiple "duplicates", getting the most recent查询具有多个“重复”的表,获取最新的
【发布时间】:2021-10-26 10:25:03
【问题描述】:

我有一个表格,用于存储来自机器学习模型的预测。 这是一个模型,每小时(“predicted_at”)预测接下来 24 小时的值(“predicted_for”)。这意味着该表对于每个“id”和“predicted_for”都有许多不同的值。

一个 ID 和一个 predict_for 时间戳的表格外观示例:

value id predicted_at predicted_for
0.1825819489860161 6970631400382957 2021-08-21 16:00:00 UTC 2021-08-21 23:00:00 UTC
0.14882256844401498 6970631400382957 2021-08-21 17:00:00 UTC 2021-08-20 23:00:00 UTC
0.17357749613149909 6970631400382957 2021-08-21 17:00:00 UTC 2021-08-21 23:00:00 UTC
0.20283864055714163 6970631400382957 2021-08-21 18:00:00 UTC 2021-08-21 23:00:00 UTC
0.18582932551434195 6970631400382957 2021-08-21 19:00:00 UTC 2021-08-21 23:00:00 UTC
0.18859835855398877 6970631400382957 2021-08-21 20:00:00 UTC 2021-08-21 23:00:00 UTC
0.15969341546283378 6970631400382957 2021-08-21 21:00:00 UTC 2021-08-21 23:00:00 UTC
0.21578765348925422 6970631400382957 2021-08-21 22:00:00 UTC 2021-08-21 23:00:00 UTC

我想要做的是查询这些数据,以便对于每个 ID,每个“predicted_for”时间只有一个预测值,并且我希望这个值在“predicted_for - t(2 ) 小时”。

例如,结果会给我下表:

value id predicted_at predicted_for
0.15969341546283378 6970631400382957 2021-08-21 21:00:00 UTC 2021-08-21 23:00:00 UTC

我假设我会有某种 group by 和一个 having 子句,但我还没有想出如何解决它。

有人有想法吗?

【问题讨论】:

  • 编辑您的问题并显示您想要的结果。从您的解释中不清楚您想要哪些行或值。 t(2) 是什么?
  • @GordonLinoff 问题已编辑。

标签: sql date datetime google-bigquery


【解决方案1】:

考虑以下方法

select any_value(value) value, id, 
  any_value(predicted_at) predicted_at, predicted_for,   
from data t
where predicted_at = predicted_for - interval 2 hour
group by id, predicted_for          

如果应用于您问题中的样本数据 - 输出是

【讨论】:

    【解决方案2】:

    您的查询应如下所示:

    SELECT * 
    FROM `YOURTABLE`
    WHERE DATETIME_DIFF(predicted_for, predicted_at, HOUR) = 2
    

    请注意,这并不能确保您只有一条记录与 predict_at 比 predict_for 中的值早 2 小时这一规则相匹配。 为了确保这一点,查询应该是这样的:

    SELECT * 
    FROM `YOURTABLE` tab
    WHERE predicted_at = (
        SELECT MAX(predicted_at)
        FROM `YOURTABLE` tab2
        WHERE DATETIME_DIFF(tab2.predicted_for, tab2.predicted_at, HOUR) = 2
        AND tab2.id = tab.id
    )
    

    【讨论】:

      【解决方案3】:

      执行如下查询:

      SELECT p.* FROM
        ( SELECT max(predicted_at) as predicted_at_max 
          FROM youraboveschowedtable 
          GROUP BY id ) p1,
      DATEADD(hour, -2, predicted_at) as predicted_minus2
      JOIN youraboveschowedtable p
      ON p.predicted_at = p1.predicted_at_max
      

      很少改变来源 = SQL query return duplicate with most recent date and more

      【讨论】:

        猜你喜欢
        • 2020-09-16
        • 2021-05-03
        • 1970-01-01
        • 1970-01-01
        • 2016-01-29
        • 2018-02-21
        • 2021-07-20
        • 2021-12-29
        • 1970-01-01
        相关资源
        最近更新 更多