Given the following table structure:
CAT | NR | DATE | VERSION | SOME_CODE |
---|---|---|---|---|
ABC | 123 | 2009-02-19T00:00:00Z | 1 | OPP |
ABC | 456 | 2009-03-18T00:00:00Z | 1 | ZUM |
ABC | 444 | 2009-03-18T00:00:00Z | 1 | ZUM |
ABC | 456 | 2009-04-18T00:00:00Z | 2 | XXX |
ABC | 456 | 2009-04-18T00:00:00Z | 3 | XXX |
ABC | 456 | 2009-04-18T00:00:00Z | 4 | UIO |
ABC | 456 | 2009-05-18T00:00:00Z | 5 | RQA |
ABC | 444 | 2009-03-18T00:00:00Z | 2 | MUZ |
DEF | 789 | 2018-02-17T00:00:00Z | 1 | WER |
DEF | 637 | 2018-02-16T00:00:00Z | 1 | FAW |
GHI | 248 | 2018-02-17T00:00:00Z | 1 | QWE |
GHI | 248 | 2019-02-17T00:00:00Z | 2 | PPP |
GHI | 357 | 2020-02-16T00:00:00Z | 1 | FFF |
GHI | 357 | 2020-02-16T00:00:00Z | 2 | GGG |
GHI | 357 | 2020-02-16T00:00:00Z | 3 | LLL |
GHI | 357 | 2020-02-16T00:00:00Z | 4 | LLL |
GHI | 357 | 2020-08-16T00:00:00Z | 4 | FFF |
GHI | 357 | 2020-10-16T00:00:00Z | 5 | ZZZ |
GHI | 420 | 2020-02-16T00:00:00Z | 1 | QDS |
I need to find out how many effective changes took place in column SOME_CODE (sometimes values are the same and therefore they should not count) per month and category (CAT).
So expected SQL query result should like this:
CAT | MONTH | SOME_CODE_CHANGES |
---|---|---|
ABC | APR 2009 | 1 |
ABC | MAR 2009 | 1 |
GHI | FEB 2020 | 2 |
Does anybody have a hint how to start the query?
Within a category (e.g. ABC) I want to count number of changes in column SOME_CODE. When a changed happened (e.g. for NR=456) say from VERSION 1 to 2 ("ZUM" -> "XXX") I wanna count it but with two conditions:
- must be a change within a month
- must be an effective change. Means the change from VERSION 3 to VERSION 4 is a valid change ("XXX" -> "UIO") while the change from VERSION 2 to VERSION 3 is nonesense ("XXX" -> "XXX") and should not be counted
My approach:
select
trunc(DATE, 'MON'),
CAT,
sum(case when _MY_CONDITION_ then 1 else 0 end) counter
from table where date between TO_TIMESTAMP('01/06/2018 00:00:00.000000000', 'DD/MM/YYYY HH24:MI:SS.FF') and TO_TIMESTAMP('31/07/2018 00:00:00.000000000', 'DD/MM/YYYY HH24:MI:SS.FF')
group by
trunc(DATE, 'MON'),
CAT
order by
trunc(DATE, 'MON')
ABC
toDEF
and then back toABC
? Is that one or two changes? – MT0CAT
, sameDATE
and sameSOME_CODE
. How do you order such rows? "By date" doesn't suffice, since they have exactly the same timestamp. And, of course, different order may result in different counts of "changes". 2. If the value changes from'ZUM'
on February 26 to'ZAM'
on March 2, is that a "change" you count for March? In almost any sane business use case the answer should be "yes" - but your explanation is confusing enough that MT0 assumed "no" for his answer. Please clarify. – mathguy