如何为每条记录选择一封电子邮件

时间:2016-06-27 07:55:00

标签: sql oracle oracle10g greatest-n-per-group

任何人都可以帮我如何为每封电子邮件选择一条记录吗?

我有以下查询:

SELECT a.ID, a.NAME, a.LASTMODIFIED, b.EMAIL
FROM TABLE_A a
JOIN TABLE_B b
ON a.IDA = b.IDB
WHERE a.LASTMODIFIED <= today
ORDER BY b.LASTMODIFIED

将导致:

+------+-------+--------------------------------------+
| id   | name   | lastmodified      | email           |
+------+-------+--------------------------------------+
| 1    | aa     | 01-JAN-2016       | test01@mail.com |
| 2    | bb     | 02-JAN-2016       | test02@mail.com |
| 3    | cc     | 03-JAN-2016       | test01@mail.com |
| 4    | dd     | 02-JAn-2016       | test03@mail.com |
+------+-------+--------------------------------------+

预期结果是:

+------+-------+--------------------------------------+
| id   | name  | lastmodified       | email           |
+------+-------+--------------------------------------+
| 2    | bb    | 02-JAN-2016        | test02@mail.com |
| 3    | cc    | 03-JAN-2016        | test01@mail.com |
| 4    | dd    | 02-JAN-2016        | test03@mail.com |
+------+-------+--------------------------------------+

每行只能返回一封电子邮件,按lastmodified日期排序。

2 个答案:

答案 0 :(得分:1)

使用ROW_NUMBER窗口功能

Select id, name, lastmodified, email     
(
Select 
Row_Number()over(partition by email order by lastmodified desc) As Rn,
..
)
Where RN = 1

答案 1 :(得分:0)

如果您想要上传的电子邮件,可以使用

SELECT a.ID, a.NAME, a.LASTMODIFIED, b.EMAIL
FROM TABLE_A a
JOIN TABLE_B b ON a.IDA = b.IDB
WHERE a.LASTMODIFIED <= today
AND   (a.LASTMODIFIED,  b.EMAIL) in  (
    SELECT max(c.LASTMODIFIED), d.EMAIL
            FROM TABLE_A c
            JOIN TABLE_B d ON c.IDA = d.IDB
            WHERE a.LASTMODIFIED <= today
            GROUP BY d.EMAIL
    )
ORDER BY b.LASTMODIFIED