Search code examples
sqlteradatardbmsteradata-sql-assistant

Teradata Scenario


Given:-

When DML_OPeration is Insert "I" then B=0 When DML_OPeration is Delete "D" then B will hold the value of A of inserted record

Condition :-

  1. if COUNT OF 'I' = Count of 'D', then we don't need those records. for example : ID=111
  2. Find latest insert('I') DML_operation
    ID  A   B   DML_Operation
1   111 1   0   I
2   111 2   1   D
3   111 3   0   I
4   111 4   3   D
5   111 5   0   I
6   111 6   5   D
7   111 7   0   I
8   222 8   0   I
9   333 9   0   I
10  333 10  9   D
11  444 11  0   I
12  444 12  11  D
13  444 13  0   I
14  111 14  7   D
15  333 15  0   I
16  444 16  0   I
17  444 17  13  D

Desire Output

ID  A   B   DML_Operation
-------------
222 8   0   I
333 15  0   I
444 16  0   I

My logic which is not working

sel ID, Max(A) from xyz
group by ID
having count(c='I') <> COUNT(c='D')

Solution

  • does you find like below

        select ID, Max(A) from xyz
        group by ID
        having sum(case when c='I' then 1 else 0 end) <> sum(case when c='D' then 1 else 0 end)