[英]Joining 3 tables with Conditional Aggregation
我正在研究如何為以下數據查找用戶的訂單擴展率。 所有訂單都在 Order 表中,所有 Orderitems 都存儲在 RentalItems 中。 一個訂單可以包含 1 個或多個項目。 如果用戶延長任何 1 項,這意味着訂單被延長。 所以我想通過檢查Total OrderExtensionsByUser/TotalOrdersPlacedByUser來找出用戶的訂單延期率
用戶表:UserID、fname、LName、Position、
訂單表:用戶 7 下了 2 個訂單,用戶 3 下了 3 個訂單
訂單編號 | 用戶身份 |
---|---|
1 | 7 |
2 | 3 |
3 | 7 |
4 | 3 |
5 | 3 |
出租物品:
租借物品 ID | 訂單編號 | 物品編號 |
---|---|---|
1 | 1 | 3 |
2 | 1 | 4 |
3 | 2 | 5 |
4 | 2 | 6 |
5 | 2 | 9 |
6 | 3 | 7 |
7 | 4 | 11 |
8 | 5 | 12 |
RentalExtions : 訂單 1 和 2 均已延期,因為該訂單中的一件以上或多於 1 件商品已延期
租借物品 ID | ExtensionBy_UserID | 延長日期 |
---|---|---|
1 | 7 | 2020-07-20 |
2 | 7 | 2020-03-05 |
3 | 3 | 2020-03-05 |
8 | 3 | 2020-03-05 |
所以在這種情況下,對於用戶 7 和 3,它應該是,
TotalOrderExtensionsByUser/AllOrdersPlacedByUser :
所需的 output (適用於所有用戶,不適用於特定用戶)
用戶身份 | 名稱 | 名稱 | 提取率 |
---|---|---|---|
7 | 喬恩 | 史密斯 | 0.50 |
3 | 史密斯 | 塔克 | 0.66 |
有什么可能的方法嗎?
下面是我之前工作過的代碼,也是由 stackOverflow 上的用戶提供的。 但我意識到它只檢查 ExtensionTable 中用戶的擴展率。 但實際上,我正在尋找的是不同的。
這段代碼將在 RentalExtensions 中查看,並給我 output 為用戶 3 的 2/4=0.40。但我需要的是不同的,正如我在上面解釋的那樣。
select UserID, fname, lname, JobTitle,
(select avg(case when re.ExtensionBy_UserID = r.userId then 1.0 else 0 end)
from RentalExtensions re
cross apply (values (userId) ) r(userId)
) as ExtensionRate from [user]
where userID in (select distinct ExtensionBy_UserID from RentalExtensions) and JobTitle = 'Support Staff'
編輯1:
ExtentendedBy_UserID
,因為它將是擴展訂單的同一個人。我認為這可能有效...如果您提供 DDL+DML,我會為您測試。
select U.UserId, convert(decimal(9,2),sum(HasExtension) / count(*))
from (
select OrderId, UserId
-- To ensure the sum is decimal not int
, convert(decimal(9,2),case when exists (select 1 from RentalExtions E where E.RentalItemId in (select RI.RentalItemId from RentalItem RI where RI.OrderId = O.OrderId)) then 1 else 0 end) HasExtension
from [Order] O
) O
inner join [User] U on U.UserId = O.UserId
group by U.UserId;
我強烈建議您在以后的所有問題中以 DDL+DML 的形式提供示例數據,因為這使我們更容易回答。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.