0

I want to get second entry in SQL

Consgno     Name      Entrydatetime

 111          A     01/03/2017 10:10:15
 111          A     01/03/2017 10:20:15
 111          A     01/03/2017 11:10:20
 222          B     02/03/2017 10:10:25
 222          B     02/03/2017 11:10:36
 333          C     06/03/2017 10:10:25
 333          C     07/03/2017 10:10:12
 444          D     04/03/2017 10:10:41
 444          D     04/03/2017 01:10:20
 444          D     06/03/2017 10:10:32

One Consgno has entered more than one time. And I want to output like this:

   Consgno  Name     Entrydatetime
    111      A      01/03/2017 10:20:15
    222      B      02/03/2017 11:10:36
    333      C      07/03/2017 10:10:12
    444      D      04/03/2017 01:10:20

4 Answers4

1

sql server/oracle/Postgres:

with CTE as
(
select MyTable.*, row_number() over(partition by consgno order by entrydatetime) as rn
from MyTable
)
select *
from CTE
where rn = 2
JohnHC
  • 10,935
  • 1
  • 24
  • 40
1

(Works only, if you DB supports window analytic functions)

In case, if there is chance that Entrydatetime may repeated for same Consgno, and you want second date-time wise, then you can use:

select * from (
    select   MyTable.*, 
    dense_rank() over(partition by consgno order by entrydatetime) as rnk,
    row_number() over(partition by consgno,entrydatetime order by entrydatetime) as rn
    from MyTable
) t
where  rnk = 2 and rn = 1

(Note, that if consgno have same Entrydatetime for every row, this query not returns that consgno at all.)

Oto Shavadze
  • 40,603
  • 55
  • 152
  • 236
-1

Use OFFSET command in your query eg.

SELECT DISTINCT  Consgno,Name,Entrydatetime  FROM tbl_test ORDER BY
    Consgno
LIMIT 1 OFFSET 1;

This example selects the 2nd row. The Consgno has to be DISTINCT

Abel Masila
  • 736
  • 2
  • 7
  • 25
-2

You can refer my query. Hope to help, my friend :))

With CTE
AS
(
select *, ROW_NUMBER() over (partition by Consgno order by Consgno) as Number
from Test)

select * from CTE where Number = 2
Tomato32
  • 2,145
  • 1
  • 10
  • 10