Teradata 场景

Teradata Scenario

给定:-

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

条件:-

  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

期望输出

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

我的逻辑不起作用

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

使用case怎么样?

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)

或者:

having sum(case when c = 'I' then 1
                when c = 'D' then -1
                else 0
           end) <> 0

你有没有发现像下面这样的

    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)

这将查找所有 'I' 行而不匹配 'D' 行:

SELECT *
FROM mytab AS t1
WHERE DML_Operation = 'I'
AND NOT EXISTS
 ( SELECT *
   FROM mytab AS t2
   WHERE t2.id = t1.id
     AND t2.b = t1.a 
     AND DML_Operation = 'D'
 )