【问题标题】:SQL - Grouping data by the most recent updatesSQL - 按最新更新对数据进行分组
【发布时间】:2021-10-27 17:29:52
【问题描述】:

我的查询有问题(使用 SQL Developer)。我有两张桌子 PERSON 和 DEVICE。 PERSON(person_id,姓名) DEVICE (device_id, person_id, device, version, udt)

加入的数据如下所示:

但我希望它看起来像这样:

所以基本上我想为每个人设置一行,并且该行需要包含所有设备和最近更新 (udt) 的设备的不同 udt 的详细信息 (Device_newest ) 及其版本 (Latest_version)。

我设法接近这个查询:

    select 
    PERSON.name, 
    max(case when SOFTWARE.device = 'mobile' then udt end) as mobile_udt,
    max(case when SOFTWARE.device = 'computer' then udt end) as computer_udt,
    max(case when SOFTWARE.device = 'laptop' then udt end) as laptop_udt
    
    from SOFTWARE
      left join PERSON on PERSON.person_id = SOFTWARE.person_id

    group by PERSON.name

但它没有 Device_newestLatest_version。我该怎么办?我很确定这是可行的。感谢您的帮助!

【问题讨论】:

标签: sql oracle group-by pivot case


【解决方案1】:

您可以在 Oracle 中使用keep 功能。这就是 Oracle 实现“第一个”聚合函数的方式:

select p.name, 
       max(case when s.device = 'mobile' then udt end) as mobile_udt,
       max(case when s.device = 'computer' then udt end) as computer_udt,
       max(case when s.device = 'laptop' then udt end) as laptop_udt,
       max(s.device) keep (dense_rank first order by udt desc) as latest_device,
       max(s.version) keep (dense_rank first order by udt desc) as latest_version
from SOFTWARE s left join
     PERSON p 
     on p.person_id = a.person_id
group by p.name;

【讨论】:

    【解决方案2】:

    您可以使用 PIVOT 子句 (techonthenet.com/oracle/pivot.php)。 像这样:

    SELECT * FROM
    (
        select *
        from device
          left join PERSON on PERSON.person_id = device.person_id
    )
    PIVOT
    (
      MAX(udt)
      FOR device IN ('mobile','computer','laptop')
    )
    ORDER BY name;
    

    【讨论】:

    • OP 已经能够显示这三列,但不能显示第 4 列和第 5 列。
    • 谢谢。这是正确的。我已经获得了这些最大 udt,但现在我还需要来自每个人的最新 udt 设备的信息。
    猜你喜欢
    • 2021-05-08
    • 2021-02-09
    • 2014-07-21
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2015-07-20
    相关资源
    最近更新 更多