编写查询,该查询将返回包含以下列的表: 用户ID,网站ID,用户名,总销售额,退款总额,收取的净额
我需要编写一个查询,该查询将返回一个表,此刻我正在尝试找出谢谢。
尝试选择语句,但失败。enter image description here
答案 0 :(得分:1)
我同意其他人的看法,即仅仅将其移交给他人不会对您的学习有所帮助。您需要在这里学习很多概念。如果您无法解释该问题,则提交该答案进行家庭作业可能会很尴尬(分数为0
)!
with cte_sales as
(
select
t.[User Id],
t.[Site Id],
sum(t.Amount) as [Total Sales]
from Transactions t
where t.[Transaction Type] = 'Sale'
group by t.[User Id],
t.[Site Id]
),
cte_refunds as
(
select
t.[User Id],
t.[Site Id],
sum(t.Amount) as [Total Refunds]
from Transactions t
where t.[Transaction Type] = 'Refund'
group by t.[User Id],
t.[Site Id]
)
select
u.[User Id],
u.[Site Id],
u.[Name] as [User Name],
coalesce(s.[Total Sales],0) as [Total Sales],
abs(coalesce(r.[Total Refunds],0)) as [Total Refunds],
(coalesce(s.[Total Sales],0) + coalesce(r.[Total Refunds],0)) as [Net Amount Collected]
from Users u
left join cte_sales s on s.[User Id] = u.[User Id]
and s.[Site Id] = u.[Site Id]
left join cte_refunds r on r.[User Id] = u.[User Id]
and r.[Site Id] = u.[Site Id]
order by u.[User Id],
u.[Site Id];
| User Id | Site Id | User Name | Total Sales | Total Refunds | Net Amount Collected |
|---------|---------|-----------|-------------|---------------|----------------------|
| 1 | 1 | Arthur | 120 | 120 | 0 |
| 2 | 1 | Aaron | 90 | 30 | 60 |
| 2 | 2 | Brett | 90 | 0 | 90 |