以下查询返回按总金额排序的最受欢迎的剧院和行类型组合的列表: 例如:
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 :(得分: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
答案 1 :(得分: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
语法。