联合两个SQL查询并选择最顶行

时间:2018-04-11 15:54:27

标签: sql teradata

我在SQL中有两个查询,而且我正在对它们进行联合。得到结果后,我需要按照给定唯一ID的日期降序选择第一行。我试过像下面这样的东西,但错误不断弹出。

SELECT  
   *
FROM 
    (SELECT DISTINCT 
         ACCT_NBR, ACCT_BLK_1 AS BLK_CDE, BLK_RSN_1 AS BLK_CDE_RSN,
         BLK_CDE_1_CHG_DT AS CLOSED_DT
     FROM 
         TABLE_1 
     WHERE 
         ACCT_BLK_1,'@') IN ('A') 
         AND DATE = CURRENT_DATE - 1
         AND BLK_CDE_1_CHG_DT BETWEEN '2018-04-01' AND '2018-04-10'

     UNION

     SELECT DISTINCT 
         ACCT_NBR, ACCT_BLK_2 AS BLK_CDE, BLK_RSN_2 AS BLK_CDE_RSN,
         BLK_CDE_2_CHG_DT AS CLOSED_DT
     FROM 
         TABLE_2 
     WHERE 
         ACCT_BLK_2,'@') IN ('A') 
         AND DATE = CURRENT_DATE - 1
         AND BLK_CDE_2_CHG_DT BETWEEN '2018-04-01' AND '2018-04-10')
QUALIFY ROW_NUMBER() OVER (PARTITION BY ACCT_NBR ORDER BY CLOSED_DT) = 1

1 个答案:

答案 0 :(得分:2)

当然,这个ACCT_BLK_1,'@') IN ('A')不是有效的语法,可能是剪切和粘贴问题。

当你想要前1行时,没有必要申请(UNION)DISTINCT。

SELECT  
   *
FROM 
    (SELECT 
         ACCT_NBR, ACCT_BLK_1 AS BLK_CDE, BLK_RSN_1 AS BLK_CDE_RSN,
         BLK_CDE_1_CHG_DT AS CLOSED_DT
     FROM 
         TABLE_1 
     WHERE 
         ACCT_BLK_1,'@') IN ('A') -- fix syntax
         AND DATE = CURRENT_DATE - 1
         AND BLK_CDE_1_CHG_DT BETWEEN '2018-04-01' AND '2018-04-10'

     UNION ALL

     SELECT 
         ACCT_NBR, ACCT_BLK_2 AS BLK_CDE, BLK_RSN_2 AS BLK_CDE_RSN,
         BLK_CDE_2_CHG_DT AS CLOSED_DT
     FROM 
         TABLE_2 
     WHERE 
         ACCT_BLK_2,'@') IN ('A') -- fix syntax
         AND DATE = CURRENT_DATE - 1
         AND BLK_CDE_2_CHG_DT BETWEEN '2018-04-01' AND '2018-04-10'
    ) as dt -- the table alias was missing
QUALIFY ROW_NUMBER() OVER (PARTITION BY ACCT_NBR ORDER BY CLOSED_DT) = 1

根据数据,在UNION之前应用QUALIFY可能更有效:

SELECT  
   *
FROM 
    (SELECT 
         ACCT_NBR, ACCT_BLK_1 AS BLK_CDE, BLK_RSN_1 AS BLK_CDE_RSN,
         BLK_CDE_1_CHG_DT AS CLOSED_DT
     FROM 
         TABLE_1 
     WHERE 
         ACCT_BLK_1,'@') IN ('A') -- fix syntax
         AND DATE = CURRENT_DATE - 1
         AND BLK_CDE_1_CHG_DT BETWEEN '2018-04-01' AND '2018-04-10'
      QUALIFY ROW_NUMBER() OVER (PARTITION BY ACCT_NBR ORDER BY CLOSED_DT) = 1

     UNION ALL

     SELECT 
         ACCT_NBR, ACCT_BLK_2 AS BLK_CDE, BLK_RSN_2 AS BLK_CDE_RSN,
         BLK_CDE_2_CHG_DT AS CLOSED_DT
     FROM 
         TABLE_2 
     WHERE 
         ACCT_BLK_2,'@') IN ('A') -- fix syntax
         AND DATE = CURRENT_DATE - 1
         AND BLK_CDE_2_CHG_DT BETWEEN '2018-04-01' AND '2018-04-10'
     QUALIFY ROW_NUMBER() OVER (PARTITION BY ACCT_NBR ORDER BY CLOSED_DT) = 1
    ) as dt -- the table alias was missing
QUALIFY ROW_NUMBER() OVER (PARTITION BY ACCT_NBR ORDER BY CLOSED_DT) = 1