简体   繁体   中英

sql oracle how to count value increases in column

I need help counting the number of times a column's value increased and decreased for a certain ID.

I have data that looks like this

ID  Month   Value1  
1   1   500  
1   2   500  
1   3   500  
1   4   1000  
2   1   1000  
2   2   500  
2   3   500  
2   4   1000  
3   1   6000  
3   2   6000  
3   3   5000  
3   4   5000  

And I want this

ID  Increases   Decreases  
1   1   0  
2   1   1  
3   0   1  

Thank you!

Create a calculated column using the lead function which gets the values from the next row. Then aggregate based on the calculated column.

select id,
count(case when inc_or_dec = 'increase' then 1 end) increases,
count(case when inc_or_dec = 'decrease' then 1 end) decreases
from (
select id,
case 
when coalesce(lead(value1) over(partition by id order by mth),value1) > value1 then 'increase'
when coalesce(lead(value1) over(partition by id order by mth),value1) < value1 then 'decrease'
when coalesce(lead(value1) over(partition by id order by mth),value1) = value1 then 'no change'
end inc_or_dec
from tablename) t
group by id

Only for fun ;) with sign function:

  SELECT id, SUM (SIGN (di + 1)) incCount, SUM (SIGN (di - 1)*-1) decCount
    FROM (SELECT id, SIGN (LEAD (value1, 1) OVER (PARTITION BY id ORDER BY id, month) - value1) di FROM TABLENAME)
   WHERE di <> 0
GROUP BY id

Here is a solution based on the lag window aggregate function:

SELECT   id,
         count(CASE WHEN value > prev_value THEN 1 END) Increases,
         count(CASE WHEN value < prev_value THEN 1 END) Decreases
FROM     (SELECT id,
                 month,
                 value,
                 lag(value) OVER (PARTITION BY id ORDER BY month) AS prev_value
          FROM   mytable)
GROUP BY id

If you just run the inner query, you can see how it puts the previous value next to the current value in each record.

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