根据一系列列返回最新日期

时间:2020-07-01 17:40:08

标签: sql google-bigquery

我有一个查询,该查询会计算已完成任务的数量并返回原始值。

我想添加新列以返回最近的日期(在这种情况下为task_1_completed_datetask_2_completed_date,但实际上有20个任务字段)

     (CASE WHEN task_1_completed_date IS NOT NULL THEN 1 ELSE 0 END +
        CASE WHEN task_2_completed_date IS NOT NULL THEN 1 ELSE 0 END
       ) AS task_completed_total 
from (select JSON_EXTRACT_SCALAR(data, '$.task1.date') as task_1_completed_date
             JSON_EXTRACT_SCALAR(data, '$.task2.date') as task_2_completed_date
      from table
      WHERE pet_store = 'london'
     )

不确定如何继续,是否应该在此处使用子查询来排序任务完成日期?

2 个答案:

答案 0 :(得分:1)

我认为您可以使用GROUP BY和MAX来获取最新日期。参见此处:https://docs.microsoft.com/en-us/sql/t-sql/queries/select-group-by-transact-sql?view=sql-server-ver15

答案 1 :(得分:1)

使用订单依据

  (CASE WHEN task_1_completed_date IS NOT 
  NULL THEN 1 ELSE 0 END +
    CASE WHEN task_2_completed_date IS NOT 
     NULL THEN 1 ELSE 0 END
   ) AS task_completed_total 
    from (select JSON_EXTRACT_SCALAR(data, 
      '$.task1.date') as task_1_completed_date
         JSON_EXTRACT_SCALAR(data, 
     '$.task2.date') as task_2_completed_date
   from table
  WHERE pet_store = 'london'
  )where rownum=1 order by 
  task_completed_total desc 
  -- if rownum doesn't work use Limit 1