获取最短约会作为条件

时间:2017-08-24 08:55:35

标签: sql teradata

我有一张表格,其中包含所有电话号码的发票,每个号码都有多张发票,我只想显示第一张确认号码的发票,但我真的不知道如何只获得第一张发票,这是我的查询

SELECT
     b.contrno
     a.AR_INVDATE
     FROM P_STG_TABS.IVM_INVOICE_RECORD a 

     INNER JOIN P_EDW_TMP.invoice b
     ON b.contrno=a.contrno

     WHERE a.AR_INVDATE< (SELECT AR_INVDATE FROM P_STG_TABS.IVM_INVOICE_RECORD WHERE contrno=b.contrno  )

3 个答案:

答案 0 :(得分:3)

Teradata支持QUALIFY子句来过滤OLAP函数的结果(类似于HAVING之后的GROUP BY),这大大简化了Tim Biegeleisens的回答:

SELECT *
FROM P_STG_TABS.IVM_INVOICE_RECORD a 
INNER JOIN P_EDW_TMP.invoice b
   ON b.contrno = a.contrno
QUALIFY
   ROW_NUMBER()
   OVER (PARTITION BY b.contrno 
         ORDER BY a.AR_INVDATE)  = 1

此外,您可以在加入之前应用ROW_NUMBER(可能更高效,具体取决于其他条件):

SELECT *
FROM 
 ( SELECT * 
   FROM P_STG_TABS.IVM_INVOICE_RECORD a 
   QUALIFY
      ROW_NUMBER()
      OVER (PARTITION BY b.contrno 
            ORDER BY a.AR_INVDATE)  = 1
 ) AS a
INNER JOIN P_EDW_TMP.invoice b
   ON b.contrno = a.contrno

答案 1 :(得分:2)

使用ROW_NUMBER()

SELECT
    t.contrno,
    t.AR_INVDATE
FROM
(
    SELECT
        b.contrno,
        a.AR_INVDATE,
        ROW_NUMBER() OVER (PARTITION BY b.contrno ORDER BY a.AR_INVDATE) rn
    FROM P_STG_TABS.IVM_INVOICE_RECORD a 
    INNER JOIN P_EDW_TMP.invoice b
        ON b.contrno = a.contrno
) t
WHERE t.rn = 1;

如果您担心关系,并且想要显示所有关系,那么您可以将ROW_NUMBER替换为RANKDENSE_RANK

答案 2 :(得分:1)

如果我理解正确,那么一种方法就是将group bymin(a.AR_INVDATE)一起使用:

SELECT
b.contrno,
min(a.AR_INVDATE)
FROM P_STG_TABS.IVM_INVOICE_RECORD a 
INNER JOIN P_EDW_TMP.invoice b
ON b.contrno=a.contrno
group by b.contrno