SQL查询比较列值

时间:2019-03-18 20:15:22

标签: sql teradata

我具有以下数据模式,需要编写SQL来验证测试方案,如下所示。这只是我的表具有数百万条记录且需要sql进行验证的示例。任何帮助/建议将不胜感激。

  
      
  1. RANK_ORDER 2的EFEC_FROM = RANK_ORDER = 1的EFEC_2
  2.   
  3. RANK_ORDER 3的EFEC_FROM = RANK_ORDER = 2的EFEC_2
  4.   
  5. RANK_ORDER的EFEC_FROM为4 = RANK_ORDER的EFEC_2为3
  6.   

数据:

S_KEY FLAG_1  FLAG_2    EFEC_FROM                   EFEC_2                     RANK_ORDER   
100   1       0         2019-02-28 15:04:00.000000  2019-02-28 15:13:00.006000  1
100   0       0         2019-02-28 15:13:00.006000  2019-02-28 15:19:00.011000  2
100   0       0         2019-02-28 15:19:00.011000  2019-02-28 15:20:00.014000  3
100   0       1         2019-02-28 15:20:00.014000  2099-12-31 00:00:00.000000  4

2 个答案:

答案 0 :(得分:0)

要找出哪些行未通过验证规则,可以使用LAG()LEAD()函数,如下所示:

with 
x as (
  select
    s_key, flag_1, flag_2, efec_from, efec_2, rank_order,
    lag(efec_2 order by rank_order) prev_efec_2
from my_table
)
select *
from x
where efec_from <> prev_efec_2

答案 1 :(得分:0)

您肯定需要使用LAG / LEAD函数从数据集中的上一行或下一行获取信息。

SELECT * FROM (
SELECT s_key,
       flag_1,
       flag_2,
       efec_from,
       efec_2,
       rank_order
       NVL (   LEAD (efec_from, 1)
               OVER (PARTITION BY s_key 
                         ORDER BY rank_order),
               '2099-12-31') AS next_efec_2
  FROM table)
WHERE efec_2 <> next_efec_from

LAG / LEAD信息的其他来源:https://docs.teradata.com/reader/756LNiPSFdY~4JcCCcR5Cw/NbZIb7BVEkYT9tMbXxOuog