I have the following tables exactly as follows
Order
OrderID | UserID |
---|---|
1 | 7 |
2 | 1 |
3 | 13 |
4 | 7 |
RentalItems
RentalItemsID | ItemID | ReturnTypeID | OrderID |
---|---|---|---|
1 | 9 | 5 | 1 |
2 | 3 | 4 | 2 |
3 | 4 | 5 | 2 |
4 | 5 | 5 | 2 |
5 | 10 | 4 | 3 |
6 | 11 | 4 | 4 |
7 | 14 | 5 | 4 |
ReturnTypeID 5: Defect Return
ReturnTypeID 4: Normal Return
select [order].UserID,
(
select avg(case when ReturnTypeID = 5 then 1.0 else 0 end) as DefectedRate
from RentalItems
where RentalItems.OrderID = [Order].OrderID
) as DefectedReturnRate
from [Order]
where OrderID in (select OrderID from RentalItems where ReturnTypeID=5)
Current Output: Calculated as: DefetedReturnByUserPerOrder/AllReturnsByUserPerOrder
UserID | DefectReturnRate | Showing Calculation, (Not incl. in output) |
---|---|---|
7 | 1.00 | Order1: 1/1 - Contained 1 item and it was defected returned |
1 | 0.66 | Order2: 2/3 - Contained 3 items and 2 were defected returned |
7 | 0.50 | Order4: 1/2 - Contained 2 items and 1 was defected returned |
as you can see, it is calculating DefetecedReturnRate per each Order and not total Items rented by user across ALL Orders
Desired Output: TotalDefetedReturnByUserForALLOrders/AllReturnsByUserForAllOrders
UserID | DefectReturnRate | Showing Calculation, (Not incl. in output) |
---|---|---|
7 | 0.66 | Order1&4: 2/3 - Total Rented items by User 7 were 3 and 2 were defected Returns |
1 | 0.66 | Order2: 2/3 - Contained 3 items and 2 were defected returned |
I think this will be my last question so any help will be greatly appreciated. I can provide DML+DDL data but I'm not sure how to. I tried to generate scripts but it was only generating tables and not data. but the tables and data is exactly as I have entered in tables above.