如何获取其他列不在oracle select sql中的GROUP BY子句中?

时间:2017-10-27 11:59:32

标签: sql oracle group-by greatest-n-per-group

我有一个包含这些数据的MOVIE表。

MOVIE_ID  MOVIE_TITLE              CATEGORY        SALES_AMT
--------- ------------------------ --------------- ----------
M_0000004 The Boss Baby            Animation       2000
M_0000006 Star Wars: The Last Jedi Science Fiction 3000
M_0000007 Get Out                  Horror          4000
M_0000008 Million Dollar Arm       Action          2000
M_0000009 The Conjuring            Horror          1000
M_0000012 The Dark Knight          Action          3000

对于SALES_AMT

,我需要基于CATEGORY的热门电影数据

所需的结果是:

MOVIE_ID  MOVIE_TITLE              CATEGORY        SALES_AMT
--------- ------------------------ --------------- ----------
M_0000004 The Boss Baby            Animation       2000
M_0000006 Star Wars: The Last Jedi Science Fiction 3000
M_0000007 Get Out                  Horror          4000
M_0000012 The Dark Knight          Action          3000

如果我使用GROUP_BY选项,则无法选择MOVIE_IDMOVIE_TITLE

select CATEGORY, MAX(SALES_AMT)
from MOVIE
group by CATEGORY
;

3 个答案:

答案 0 :(得分:3)

尝试使用分析函数和子查询

select movie_id, movie_title, category, sales_amt 
from (
  select movie_id, movie_title, category, sales_amt, 
  row_number() over (partition by category order by sales_amt desc) r 
  from movie
) where r = 1

答案 1 :(得分:0)

您可以使用RANK()来实现此目的:

SELECT
    MOVIE_ID
    , MOVIE_TITLE
    , CATEGORY
    , SALES_AMT
FROM
    (
        SELECT
            MOVIE_ID
            , MOVIE_TITLE
            , CATEGORY
            , SALES_AMT
            , RANK() OVER (PARTITION BY CATEGORY ORDER BY SALES_AMT DESC) RNK
        FROM MOVIE
    ) Q
WHERE RNK = 1

如果您希望在结果中看到重复项(销售额相等),则会将RANK替换为ROW_NUMBER

答案 2 :(得分:0)

我们先说你先运行这个:

SQL> select deptno, min(sal)
  2  from emp
  3  group by deptno;

然后想要让拥有最低工资的员工。然后这当然失败了:

SQL> select deptno, empno, min(sal)
  2  from emp
  3  group by deptno;

ORA-00979: not a GROUP BY expression

但是你可以使用KEEP语法和窗口函数来协助

SQL> select deptno, min(sal), min(empno) 
  2    KEEP ( dense_rank FIRST order by sal) empno
  3  from emp
  4  group by deptno
  5  /

    DEPTNO   MIN(SAL)      EMPNO
---------- ---------- ----------
        10       1300       7934
        20        800       7369
        30        950       7900

其中这被解读为" EMPNO 7934是薪水为1300"

的人