1

Can anyone help me how to select one record per email?

I have the query below:

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

it will result :

+------+-------+--------------------------------------+
| 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 |
+------+-------+--------------------------------------+

expected result is :

+------+-------+--------------------------------------+
| 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 |
+------+-------+--------------------------------------+

It should return only one email per row, order by lastmodified date.

MT0
  • 143,790
  • 11
  • 59
  • 117
tukimin
  • 53
  • 6

2 Answers2

1

Use ROW_NUMBER window function

Select id, name, lastmodified, email     
(
Select 
Row_Number()over(partition by email order by lastmodified desc) As Rn,
..
)
Where RN = 1
Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
0

If you want the last email you can use

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
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107