当我有这样的桌子时,每月获得最佳销售团队的最佳方法是什么:
结果应该是这样的(按订单总价分组):
Month | Team | Sales
____________________
March | 2 | 3453
April | 3 | 1353
May | 2 | 5341
我之前已经加入了两个表,但是由于某种原因,加入4个表并按月分组似乎很困难。 谢谢。
答案 0 :(得分:1)
这应该做到。我也加了一年。它使用CTE
with cte as
(
select Team_nr, sum(price) as Sales, date_part('month', Created) as _Month, date_part('year', Created) as _Year
from employee e
inner join orders o on e.id = o.employee_ID
inner join products p on p.id = orders.product_id
Group by Team_nr, date_part('month', Created), date_part('year', Created)
)
select Team_nr, Sales, _Month, _Year
from cte a
where not exists(select 1 from cte b where
a._Month = b._Month and a._Year = b._Year and a.Team_nr <> b.Team_nr and a.Sales < b.Sales )
答案 1 :(得分:1)
在Postgres中,您可以使用distinct on
-如果您每月只需要一行:
select date_trunc('month', created), e.Team_nr, sum(p.price) as Sales
from employee e join
orders o
on e.id = o.employee_ID join
products p
on p.id = orders.product_id
group by e.Team_nr, date_trunc('month', o.Created)
order by date_trunc('month', o.Created), sum(p.price) desc