Oracle SQL查询,获得最多的总和

时间:2017-12-11 18:58:35

标签: sql oracle

嘿,伙计们。我很难解决一个问题,只是无法绕过它。

基本上,我从数据集市获得了一些表:

 DimTheatre(TheatreId(PK), TheatreNo, Name, Address, MainTel);
 DimTrow(TrowId(PK), TrowNo, RowName, RowType);
 DimProduction(ProductionId(PK), ProductionNo, Title, ProductionDir, PlayAuthor);
 DimTime(TimeId(PK), Year, Month, Day, Hour);
 TicketPurchaseFact( TheatreId(FK), TimeId(FK), TrowId(FK),
 PId(FK), TicketAmount);

我想在oracle中实现的目标是 - 我需要通过售票价值检索每个影院中最受欢迎的行类型

我现在正在做的事情是:

SELECT dthr.theatreid, dthr.name, max(tr.rowtype) keep(dense_rank last order 
by tpf.ticketamount), sum(tpf.ticketamount) TotalSale
FROM TicketPurchaseFact tpf, DimTheatre dthr, DimTrow tr
WHERE dthr.theatreid = tpf.theatreid
GROUP BY dthr.theatreid, dthr.name;

它确实给了我输出,但是' TotalSale'专栏是完全不合适的,它提供了比他们应该更多的数字。我怎么能处理这个问题:)?

2 个答案:

答案 0 :(得分:1)

如果我正确理解问题,我不确定MAX()KEEP()如何帮助你的情况。但是下面的方法应该有效:

SELECT x.theatreid, x.name, x.rowtype, x.total_sale
FROM
    (SELECT z.theatreid, z.name, z.rowtype, z.total_sale, DENSE_RANK() OVER (PARTITION BY z.theatreid, z.name ORDER BY z.total_sale DESC) as popular_row_rank
    FROM
        (SELECT dthr.theatreid, dthr.name, tr.rowtype, SUM(tpf.ticketamount) as total_sale
        FROM TicketPurchaseFact tpf, DimTheatre dthr, DimTrow tr
        WHERE dthr.theatreid = tpf.theatreid AND tr.trowid = tpf.trowid
        GROUP BY dthr.theatreid, dthr.name, tr.rowtype) z
    ) x
WHERE x.popular_row_rank = 1;

答案 1 :(得分:1)

您希望每个影院的行类型具有最高票数。因此,加入购买和行,然后聚合以获得每行类型的总数。使用RANK对每个影院的行类型进行排名,并保持最佳排名。最后加入剧院桌以获得剧院名称。

select
  theatreid,
  t.name,
  tr.trowid
from
(
  select 
    p.theatreid, 
    r.rowtype, 
    rank() over (partition by p.theatreid order by sum(p.ticketamount) desc) as rn
  from ticketpurchasefact p
  join dimtrow r using (trowid)
  group by p.theatreid, r.rowtype
) tr
join dimtheatre t using (theatreid)
where tr.rn = 1;