[英]SQL Query with multiple columns and an aggregate function using GROUP BY
我的 SQL 查詢有問題。 我有以下movie
表:
Name Null? Type
----------------------------------------- -------- ----------------------------
ID_MOVIE NOT NULL NUMBER(4)
TITLE NOT NULL VARCHAR2(30)
GENRE NOT NULL VARCHAR2(30)
YEAR NOT NULL NUMBER(4)
COUNTRY NOT NULL VARCHAR2(30)
DURATION NOT NULL NUMBER(3)
BUDGET NUMBER(10)
INCOMES NUMBER(10)
ID_MOVIE_PREV NUMBER(4)
ID_DIRECTOR
我試過這個命令: select m.genre, max(m.budget),m.title from movie m group by m.genre,m.title;
並得到了這個結果:
GENRE MAX(M.BUDGET) TITLE
------------------------------ ------------- ------------------------------
Western 1200000 The Good, the Bad and the Ugly
Horror 806947 Psycho
Crime 7000000 The Godfather: Part III
Action 185000000 The Dark Knight
Drama 26000000 Philadelphia
Drama 13000000 In the Name of the Father
Action 150000000 Batman Begins
Historical 23800000 The Last Emperor
Science-fiction 5800000 Planet of the Apes
Crime 7000000 The Godfather
Action 230000000 The Dark Knight Rises
GENRE MAX(M.BUDGET) TITLE
------------------------------ ------------- ------------------------------
Comedy 28000000 Zoolander
Crime 9000000 Pulp Fiction
Crime 13000000 The Godfather: Part II
War 70000000 Saving Private Ryan
Science-fiction 28000000 Blader Runner
Drama 33000000 Gran Torino
我想要每個性別的最大值的標題。 誰能告訴我我的錯誤在哪里? 提前謝謝你!
我懷疑您的查詢實際上並未聚合,因為您希望(genre, title)
元組在表中是唯一的。
您可以使用相關子查詢來過濾表:
select genre,title, budget
from movie m
where budget = (
select max(m1.budget)
from movie m1
where m1.genre = m.genre
)
在我看來,這似乎是表達您要實現的目標的最簡單方法。 對於性能,請考慮(genre, budget)
上的索引。
這是一個關於 DB Fiddle 的演示(基於上述假設,您當前的結果集可以被視為您的原始數據):
GENRE | TITLE | BUDGET :-------------- | :----------------------------- | --------: Western | The Good, the Bad and the Ugly | 1200000 Horror | Psycho | 806947 Historical | The Last Emperor | 23800000 Action | The Dark Knight Rises | 230000000 Comedy | Zoolander | 28000000 Crime | The Godfather: Part II | 13000000 War | Saving Private Ryan | 70000000 Science-fiction | Blader Runner | 28000000 Drama | Gran Torino | 33000000
您可以使用row_number()
解析 function:
select genre, budget,title
from
(
select genre, budget, title,
row_number() over (partition by genre order by budget desc) as rn
from movie
)
where rn = 1
分組是通過分區來執行的,預算的最大值是通過按預算降序來找到的。
在 Oracle 中,可以使用聚合:
select genre,
max(title) keep (dense_rank first order by budget desc) as title,
max(budget) as budget
from movie m
group by genre;
keep
表達式本質上是在執行獲取第一個值 function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.