简体   繁体   中英

How to check the Row count Trend

My scenario: I want to check the row count trend i want to check the today record count against the avg of past 5 days count and if the threshold value is more than 10% then i want to display the result

I have the below data and table name is AGENT and the count of records loaded for the inserted_date"4/4/2021" is 5 and count of records loaded for the inserteddate"4/5/2021" is 6 and count of records loaded for the inserteddate"4/6/2021" is 1

so my query should check the latest inserteddate "4/6/2021" and the count of record is 1 which is greater than the threshold value of 10% that is average count of past 2 days is 5.5

i want the result to be populated as 1 if the count of avg is not matching with the averge of past 2 days then the output should be 0 if the trend is matching

Please help on this

在此处输入图像描述

You can use aggregation and window functions. Something like this:

select (case when cnt < avg_cnt * 0.9 then 1 else 0 end) as matching_flag
from (select inserteddt, count(*) as cnt,
             avg(count(*)) over (order by inserteddt rows between 2 preceding and 1 preceding) as avg_cnt,
             row_number() over (order by inserteddt desc) as seqnum
      from t
      where inserted_dt >= current_date - interval '2 day'
      group by inserteddt
     ) i
where seqnum = 1;

Date function depend notoriously on the database, but this gives an idea for how this can be done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM