Oracle SQL - 选择LEVEL最高的行

时间:2016-11-20 01:16:12

标签: sql database oracle group-by connect-by

我的查询如下:

SELECT CONNECT_BY_ROOT(name), LEVEL
  FROM Workers
  CONNECT BY PRIOR boss=nick
  START WITH function IN ('programmer', 'designer');

我明白了:

BELLA   1
BELLA   2
BELLA   3
MICKEY  1
MICKEY  2
BOB     1
BOB     2
DUDE    1
DUDE    2
DUDE    3
SONIA   1
SONIA   2
SONIA   3
KATE    1
KATE    2
KATE    3
LUKE    1
LUKE    2
LUKE    3
LUKE    4

我想要的是获得最高等级的名字。 我的意思是:

BELLA   3
MICKEY  2
BOB     2
DUDE    3
SONIA   3
KATE    3
LUKE    4

我试过这样做:

SELECT CONNECT_BY_ROOT(name), MAX(LEVEL)
  FROM Workers
  CONNECT BY PRIOR boss=nick
  START WITH function IN ('programmer', 'designer')
  GROUP BY CONNECT_BY_ROOT(name);

但它不起作用。我得到了00979。 00000 - 不是GROUP BY表达式'错误。为什么?我怎样才能使它有效?

2 个答案:

答案 0 :(得分:2)

一种方法使用cte:

with t(name, lev) as (
      SELECT CONNECT_BY_ROOT(name), LEVEL
      FROM Workers
      CONNECT BY PRIOR boss=nick
      START WITH function IN ('programmer', 'designer')
     )
select name, max(lev)
from t
group by name;

答案 1 :(得分:2)

<强> CONNECT_BY_ISLEAF

SELECT CONNECT_BY_ROOT(name), LEVEL
FROM Workers
WHERE connect_by_isleaf = 1
CONNECT BY PRIOR boss=nick
START WITH function IN ('programmer', 'designer');