code updated:
Added [score] column to #left table. The join must pull student name and score from #left table. Any one score is fine but it should not pull duplicate student_id. I am thinking cursor can do it?
I am running this report. The problem is similar to the the script that I created. To sum up, I have two tables lets call it #left and #right. The #right table is the key one which contains the amount. But the #left table contains the agent name which I must retrieve too.
create table #left (
id int not null primary key identity,
student_id int, name varchar(20),score int)
insert into #left values( 1, 'James',10)
insert into #left values( 2, 'Parker',20)
insert into #left values( 3, 'Smith',30)
insert into #left values( 4, 'Rog',40)
insert into #left values( 1, 'James',50)
insert into #left values( 2, 'Parker',60)
create table #right (
id int not null primary key identity,
student_id int,
amount decimal(5,2)
)
insert into #right values (1,5.25)
insert into #right values (3,7.25)
insert into #right values (4,3.25)
insert into #right values (1,5.25)
The problem here is I want to join the two tables on student_id but as you can see #left table contains James and Parker 2 times with the same id. Lets assume this was database mistake.
A similar problem can exists in the #right table. But that is not a mistake. It simply means the #left student was associated with two payments (even if the two payments are the same).
I want to remove dups from #left table and keep the dups in the #right table.
I came up with this query, which works
/* query 1 */
select student_id, amount from #right R
where exists
(
select student_id from #left L
where R.student_id = L.student_id
);
But the problem here is I also need to pull the student name from the other table. Is there a way to do it. It can be any syntax but efficient query is desirable.
This should work:
Solution to the original problem
Where #left table looked like this
Query: 1
UPDATED to the modified criteria Well, if any score is fine, then you can do this:
Query: 2