Oracle: how to “group by” over a range?

后端 未结 10 1574
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 22:26

If I have a table like this:

pkey   age
----   ---
   1     8
   2     5
   3    12
   4    12
   5    22

I can \"group by\" to get a count

10条回答
  •  孤城傲影
    2020-12-07 23:20

    Here is a solution which creates a "range" table in a sub-query and then uses this to partition the data from the main table:

    SELECT DISTINCT descr
      , COUNT(*) OVER (PARTITION BY descr) n
    FROM age_table INNER JOIN (
      select '1-10' descr, 1 rng_start, 10 rng_stop from dual
      union (
      select '11-20', 11, 20 from dual
      ) union (
      select '20+', 21, null from dual
    )) ON age BETWEEN nvl(rng_start, age) AND nvl(rng_stop, age)
    ORDER BY descr;
    

提交回复
热议问题