I have a column called vs_tblRentals which has the following columns:
RENTALID CUSTOMERID BOXID RENTALDATE RETURNDATE
As well as a column called vs_tblBoxes which has the following columns
BOXID MOVIEID MEDIUMTYPECODE DATEBOXRECEIVED
I am trying to create a query that retrieve how many times each value in the BoxID column of vs_tblBoxes appears in the BoxID column of vs_tblRentals, essentially telling me how many times each box has been rented. I can do this through the following command:
SELECT COUNT(vs_tblRentals.BoxID) AS RentalCount
FROM vs_tblRentals
LEFT JOIN vs_tblBoxes B ON vs_tblRentals.BoxID = B.BoxID
GROUP BY vs_tblRentals.BoxID;
However, I also want to display information along side this RentalCount that is NOT part of the group- ideally my output would look something like this:
BoxID MovieID MediumTypeCode RentalCount
I would also like to display all the records in vs_tblRentals for the Boxes that have been rented more than 5 times.
How is this supposed to be done in Oracle 12c?
EDIT:
The following code successfully gets the Rental Count for each BoxID:
SELECT COUNT(vs_tblRentals.BoxID) AS RentalCount, vs_tblRentals.BoxID
FROM vs_tblRentals
LEFT JOIN vs_tblBoxes B ON vs_tblRentals.BoxID = B.BoxID
GROUP BY vs_tblRentals.BoxID;
And outputs the following:
RENTALCOUNT BOXID
1 337
1 691
1 43
4 321
4 123
4 665
4 674
But I cannot get this to work while displaying other information about the BoxID alongside this.
Sample Data From vs_tblBoxes:
BOXID MOVIEID MEDIUMTYPECODE DATEBOXRECEIVED
257 702 BD 22-Nov-1953
258 708 VHS 16-Jul-1988
259 708 DVD 16-Jul-1988
Sample data from vs_tblRentals
RENTALID CUSTOMERID BOXID RENTALDATE RETURNDATE
1 1 257 06-Apr-2018 22-Apr-2018
2 1 257 22-Mar-2018 NULL
3 1 259 26-Feb-2018 16-Mar-2018
What you want is probably to left join the tables in the opposite order (make entries in vs_tblRentals optional instead of the other way around), add the extra columns to the select and GROUP BY
them too.
SELECT B.BoxID, B.MovieID, B.DateBoxReceived, COUNT(R.BoxID) AS RentalCount
FROM vs_tblBoxes B
LEFT JOIN vs_tblRentals R
ON R.BoxID = B.BoxID
GROUP BY B.BoxID, B.MovieID, B.DateBoxReceived;
Using GROUP BY
on Oracle (in contrast to for example MySQL) requires you specify your query more fully and either group on each column you want to extract or generate it using an aggregate function (such as MAX
or COUNT
)
Doing neither will render an error.
Instead of left join use right outer join to do so..
select b.boxId, count(*) as RentalCount from
vs_tblRentals r right outer join vs_tblBoxes b
on b.boxId = r.boxId group by b.boxId;
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.