【问题标题】:SQL find max date based on a non null other columnSQL根据非空其他列查找最大日期
【发布时间】:2020-12-13 11:28:33
【问题描述】:

我有一张这样的桌子:

|uniqueID|scandatetime       |scanfacilityname|
+--------+-------------------+----------------+
|12345678|01-01-2020 13:45:12|BALTIMORE       |
|12345678|01-02-2020 22:45:12|BALTIMORE       |
|12345678|01-04-2020 10:15:12|PHILADELPHIA    |
|12345678|01-05-2020 08:45:12|                |

我想返回一整行,其中包含 uniqueID、scandatetime 和最新的 scanfacilityname(即最大 scandatetime,其中 scanfacilityname 不为空)。我尝试了以下查询:

SELECT
"uniqueID"
, "max"(CAST("scandatetime" AS timestamp)) "timestamp"
, COALESCE("scanfacilityname") "scanfacilityname"
FROM
iv_scans_new.scan_data
WHERE (("partition_0" = '2020') AND ("partition_1" IN ('06', '07', '08'))) and  scanfacilityname is not null
group by 1, 3
;

但我不确定这是否正确/是否需要合并。

【问题讨论】:

  • 不相关,但是:COALESCE("scanfacilityname")可以简化为"scanfacilityname"
  • 您使用的是哪种 DBMS 产品? “SQL”只是一种查询语言,而不是特定数据库产品的名称。请为您正在使用的数据库产品添加tagWhy should I tag my DBMS
  • 这是 Athena/prestodb。

标签: sql datetime greatest-n-per-group presto amazon-athena


【解决方案1】:

你可以使用max_by函数:

select max_by(uniqueID, scanfacilityname), max_by(scandatetime, scanfacilityname), max(scanfacilityname)

请参阅doc

不需要coalesce,因为maxmax_by 函数将有效地忽略null 值。

【讨论】:

    【解决方案2】:

    一种选择是使用子查询进行过滤:

    select s.*
    from iv_scans_new.scan_data s
    where s.scandatetime = (
        select max(s1.scandatetime)
        from iv_scans_new.scan_data s1
        where s1.uniqueID = s.uniqueID and s1.scanfacilityname is not null
    )
    

    你也可以使用row_number():

    select *
    from (
        select 
            s.*, 
            row_number() over(partition by uniqueID order by scandatetime desc) rn
        from iv_scans_new.scan_data s
        where scanfacilityname is not null
    ) s
    where rn = 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 2021-08-21
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      • 2018-11-03
      相关资源
      最近更新 更多