我有一张表格,其中包含所有电话号码的发票,每个号码都有多张发票,我只想显示第一张确认号码的发票,但我真的不知道如何只获得第一张发票,这是我的查询
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 )
答案 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
替换为RANK
或DENSE_RANK
。
答案 2 :(得分:1)
如果我理解正确,那么一种方法就是将group by
与min(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