【问题标题】:Select the IDs in given series in Teradata SQL在 Teradata SQL 中选择给定系列中的 ID
【发布时间】:2021-11-30 20:39:05
【问题描述】:

如何选择系列后面的id,例如对于每个id, 当条件1为11,12,13,对应条件2为null,14,16.

数据如下

id      condition1  condition2
101       11          ? 
101       13          14    
101       15          16
102       11          ?
102       13          14
102       15          16
102       17          18
103       13          14
103       15          16
104       11          ? 
104       13          14
104       15          16
104       13          14
104       15          16
105       11          ?
105       13          14

预期输出

id      condition1  condition2
101       11          ? 
101       13          14    
101       15          16
103       13          14
103       15          16
104       11          ? 
104       13          14
104       15          16
104       13          14
104       15          16

提前谢谢你

【问题讨论】:

  • 条件 1 是 11,12,13?根据预期的答案,这应该是 11、13、15。正是这三行的ID?是否存在重复行?

标签: teradata teradata-sql-assistant teradatasql


【解决方案1】:

编辑以匹配您的新逻辑。

如果没有重复行:

select *
from tab
qualify
   sum(case when condition1 = 11 and condition2 is null
            then 0 -- ignore it
            when condition1 = 13 and condition2 = 14
              or condition1 = 15 and condition2 = 16
            then  1 -- increase for specific rows
            else -1 -- decrease for any other row
        end)
   over (partition by id) = 2

不幸的是,Windowed Aggregates 不支持 DISTINCT,但有一个解决方法,只检查第一行:

select *
from 
 (
   select t.*
     ,row_number() -- check 1st row only
      over (partition by id, condition1, condition2
            order by id) as rn
   from tab as t
 ) as dt
qualify
   sum(case when rn = 1 -- check 1st row only
             and condition1 = 11 and condition2 is null
            then 0 -- ignore it
            when rn = 1 
             and (condition1 = 13 and condition2 = 14
               or condition1 = 15 and condition2 = 16)
            then  1 -- increase for specific rows
            else -1 -- decrease for any other row
        end)
   over (partition by id) = 2

【讨论】:

  • 是的,有重复的值,并且没有重复,aove 代码有效。除此之外,我还需要选择那些没有第一种情况但有其他 2 种情况的 id,条件 1 = 11 和条件 2 为空,我已经编辑了表格和预期的输出。 @dnoeth
猜你喜欢
  • 2021-09-20
  • 2011-03-06
  • 1970-01-01
  • 2018-05-11
  • 2019-04-16
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 2017-03-19
相关资源
最近更新 更多