My professor has given me an assignment.
Write a query that will produce the snum values of all salespeople (suppress the duplicates) with orders in the Orders table.
SalesPeople
Snum number(4)
Sname varchar2(10)
City varchar2(10)
Comm number(3,2)
Customer
Cnum number(4)
Cname varchar2(10)
City varchar2(10)
Rating number(4)
Snum number(4)
Orders
Onum number(4)
Amt number(7,2)
Odate date
Cnum number(4)
Snum number(4)
I am not sure if I have understood the question completely.
I have written the query using join.
select distinct s.snum,onum
from salespeople s, ordrs o
where s.snum = o.snum
order by snum;
and the output is
SNUM ONUM
---------- ----------
1001 3003
1001 3008
1001 3011
1002 3005
1002 3007
1002 3010
1004 3002
1007 3001
1007 3006
But I don't want SNUM to be repeated. Can someone point me in a right direction ?
Thanks.
The question asks you to "Write a query that will produce the snum values of all salespeople (suppress the duplicates) with orders in the Orders table" - it doesn't specify that you need to include the order numbers. (It implies that you don't need the order numbers, since by including them you will duplicate the snum values.)
Given that snum appears on the Orders table, it should be relatively simple to SELECT a DISTINCT list of SNUM values FROM the ORDERS table.
In your query remove onum from the SELECT -
select distinct s.snum
from salespeople s, ordrs o
where s.snum = o.snum
order by snum;
This should display only the distinct snum.
You only need to select from 1 table:
select distinct o.snum
from ordrs o
order by o.snum;
NB I have kept the order by clause, but it isn't strictly needed to answer the question as it was given.
Both answer above seems correct but it seems that
select distinct snum
from ordrs
order by snum
or
select snum
from ordrs
group by snum
order by snum
would be more efficient because we dont need to read the salespeople. This is acceptable if there is a foreign key constraint on snum in the table ordrs.
NB: Tony just answered when i was writing this. I would 100% agree with him :)
And it can also be easily done with a subquery instead of a join:
select s.snum
from salespeople s
where exists (
select 1
from ordrs
where snum = s.snum
);
which basically says: give me all snum's that have at least 1 matching record in the ordrs table.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.