【问题标题】:How can I retrieve the first date and last date with windows function?如何使用 windows 功能检索第一个日期和最后一个日期?
【发布时间】:2021-07-08 05:38:49
【问题描述】:

我有一些数据(表格有更多列,这是一个示例输出):

我想检索 factory_id、first_read_date、last_read_date 和 total_count。 (first_read_date, last_read_date 是基于 factory_id) 我尝试使用 windows 功能,但最后一个 read_date 不正确。 这是我所做的:

with temptable as(
select
factory_id,
read_date,
rank() over(partition by factory_id order by read_date asc) as Ranked_first_read_date,
rank() over(partition by factory_id order by read_date desc) as Ranked_last_read_data,
concat(read_date,' _ ',rank() over(partition by factory_id order by read_date asc)) as first_read_date ,
concat(read_date,' _ ',rank() over(partition by factory_id order by read_date desc)) as last_read_date,
count(*) over() as total_count
from TestDatabase.sensor_data
order by factory_id,read_date)
select * from temptable a
where Ranked_first_read_date=1 and 
Ranked_last_read_data=(select max(b.Ranked_last_read_data) from temptable b where a.factory_id=b.factory_id group by factory_id)

我正在使用 BigQuery。 任何帮助将不胜感激。

【问题讨论】:

    标签: sql group-by google-bigquery window-functions


    【解决方案1】:

    您应该尝试执行以下查询:-

    select factory_id , min(read_date) as first_read_date, max (read_date) as last_read_date  , count(*) as total_count_per_FacID,
    (select count(*) from table) as total
    FROM table
    group by factory_id 
    

    【讨论】:

    • 谢谢,这几乎是我想要的,但我必须对代码进行一些更改。我希望总行数不基于每个组。但这对我有帮助。我会接受它作为答案
    【解决方案2】:

    factory_id、first_read_date、last_read_date 和 total_count

    对窗口函数使用聚合:

    select sd.factory_id, min(sd.read_date) as first_read_date,
           max(sd.read_date) as last_read_date,
           count(*) as cnt_per_factory,
           sum(count(*)) over () as cnt_total
    from TestDatabase.sensor_data sd
    group by factory_id 
    

    【讨论】:

    • 非常感谢,我今天试试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 2012-05-29
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    相关资源
    最近更新 更多