2016-11-27 96 views
0

下面的查詢將返回按總量排序的最流行的戲劇和行類型組合的列表: 因此,例如:ORACLE - MAX和SUM

NAME  ROWTYPE TOTALAMOUNT 
theatre1 middle 200 
theatre2 front 190 
theatre1 front 150 
theatre2 middle 100 

而我需要的僅僅是每家影院的最大:

theatre1 middle 200 
theatre2 front 190 

查詢:

SELECT name, rowtype, sum 
from (select 
name, rowtype, sum(totalamount) sum from trow, fact, theatre 

Where trow.trowid = fact.trowid 
AND 
theatre.theatreid = fact.theatreid 

GROUP BY rowtype, name 
) 

ORDER BY sum DESC, name, rowtype ; 
+0

請分享trow,fact和劇團表的定義和使用sum(totalamount)的用途 –

+0

如果我們知道NAME和ROWTYPE字段來自哪些表將會很有幫助。我擔心NAME是影院名稱,因此來自THEATER,而行類型來自TROW,但留下了TOTALAMOUNT來自哪裏的問題。對問題的一些澄清會有所幫助。謝謝。 –

回答

0

您可以使用窗口功能如下:

select name, rowtype, sum 
from (select name, rowtype, sum(totalamount) as sumta, 
      max(sum(totalamount)) over (partition by name) as maxsumta 
     from trow join 
      fact 
      on trow.trowid = fact.trowid join 
      theatre 
      on theatre.theatreid = fact.theatreid 
    group byrowtype, name 
    ) nr 
where sumta = maxsumta; 

此外,你應該學會使用正確的,明確的JOIN語法。一個簡單的規則:從不FROM子句中使用逗號。 始終使用使用正確的顯式JOIN語法。

+0

嗨,非常感謝你的工作正常 –

0

把你當前的查詢放入一個公共表格表達式中,然後使用窗口函數查找每個影院的最大總量。

WITH cte AS 
(
    SELECT name, rowtype, SUM(totalamount) sum 
    FROM trow 
    INNER JOIN fact 
     ON trow.trowid = fact.trowid 
    INNER JOIN theatre 
     ON theatre.theatreid = fact.theatreid 
    GROUP BY name, rowtype 
) 

SELECT name, rowtype, sum 
FROM 
(
    SELECT name, 
      rowtype, 
      sum, 
      MAX(sum) OVER (PARTITION BY name) maxSum 
    FROM cte 
) t 
WHERE t.sum = t.maxSum 
+0

嗨,謝謝你的評論 - oracle正在返回以下錯誤ORA-00979:不是GROUP BY表達式 –

+0

@HannahFarrugia你可以再次嘗試查詢嗎? –