db2 正在从2个sql表中获取重复记录

myss37ts  于 2022-11-07  发布在  DB2
关注(0)|答案(2)|浏览(102)

我有2个SQL表
表1
| 帐目|积|有效期|
| - -|- -|- -|
| 一百零一|产品1| 2021年1月30日|
| 一百零二|产品2| 2021年2月20日|
| 一百零三|产品3| 2021年3月9日|
| 一百零三|产品3| 2021年3月19日|
| 一百零四|产品4| 2021年3月15日|
| 一百零五|产品5| 2021年4月23日|
| 一百零五|产品5| 2021年4月24日|
| 一百零六个|产品6| 2021年4月25日|
表2
| 帐目|
| - -|
| 一百零一|
| 一百零六个|
从上面的两个表中,我希望仅从Table 1中获取不匹配的记录,并避免重复记录。
结果:
| 帐目|积|有效期|
| - -|- -|- -|
| 一百零二|产品2| 2021年2月20日|
| 一百零三|产品3| 2021年3月9日|
| 一百零四|产品4| 2021年3月15日|
| 一百零五|产品5| 2021年4月23日|
我尝试了以下查询,但得到了重复记录,因为到期日期在帐户上是唯一我在输出中得到以下记录
我尝试的SQL查询:

select distinct (a.account, a.product, a.expiry-date) 
 from table1 a 
 where a.account not in (select account from table2)

结果:
| 帐目|积|有效期|
| - -|- -|- -|
| 一百零二|产品2| 2021年2月20日|
| 一百零三|产品3| 2021年3月9日|
| 一百零三|产品3| 2021年3月19日|
| 一百零四|产品4| 2021年3月15日|
| 一百零五|产品5| 2021年4月23日|
| 一百零五|产品5| 2021年4月24日|

voj3qocg

voj3qocg1#

您可以使用聚合来使用相同的查询:

SELECT a.account
  ,a.product
  ,MIN(a.expiry) expiry
 FROM table1 a
 WHERE a.account NOT IN (
    SELECT account
    FROM table2
    )
 GROUP BY a.account
   ,a.product
n3schb8v

n3schb8v2#

您可以使用反联接,然后使用ROW_NUMBER()。例如:

select *
from (
  select a.*, row_number() over(partition by accoun order by expiry) as rn
  from table1 a
  left join table2 b on b.account = a.account
  where b.account is null
) x
where rn = 1

相关问题