Skip to Main Content
  • Questions
  • Retreive userid who has taken training more than once

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Siva.

Asked: July 04, 2016 - 11:20 am UTC

Last updated: July 04, 2016 - 3:20 pm UTC

Version: 1

Viewed 1000+ times

You Asked

Hi Tom,
I have 2 tables user and training

User
Userid Username Trainingid
1 A 1
2 B 2
3 C 2
4 D 3
5 E 2


Training

Trainingid trainername userid countoftrainings Date
1 X 1 2 7/4/2016
2 Y 2 1 7/4/2016
3 Z 3 2 7/3/2016
4 I 4 3 7/3/2016
5 J 5 2 7/3/2016


Want to retrieve the user_id who has taken training more than 1 time order by date desc.


and Chris said...

So... where countoftrainings > 1?

create table usrs (
Userid int, Username varchar2(10), Trainingid int
);

create table training (
Trainingid int, trainername varchar2(10), 
userid int, countoftrainings int, dt Date  
);

insert into usrs values (1,'A', 1);
insert into usrs values (2 ,'B', 2);
insert into usrs values (3 ,'C', 2);
insert into usrs values (4 ,'D', 3);
insert into usrs values (5 ,'E', 2);

alter session set nls_date_format = 'mm/dd/yyyy';
insert into training values (1, 'X', 1, 2, '7/4/2016');
insert into training values (2, 'Y', 2, 1, '7/4/2016');
insert into training values (3, 'Z', 3, 2, '7/3/2016');
insert into training values (4, 'I', 4, 3, '7/3/2016');
insert into training values (5, 'J', 5, 2, '7/3/2016');

commit;

select u.*, t.dt from training t
join   usrs u
on     t.userid = u.userid
where  countoftrainings > 1
order  by dt desc;

    USERID USERNAME   TRAININGID DT       
---------- ---------- ---------- ----------
         1 A                   1 07/04/2016
         4 D                   3 07/03/2016
         5 E                   2 07/03/2016
         3 C                   2 07/03/2016


If this isn't it, you're going to have to provide more detail!

The user and training tables seems to reference each-other (both have userid and trainingid). This is a little strange... Only one should refer to the other. If you have a many to many relationship (a user can take multiple training sessions, each session can have multiple users on it), then you should have a join table between them:

create table user_trainings (
  user_id int, training_id int
);


Is this answer out of date? If it is, please let us know via a Comment