SELECT a,b,count(*)
FROM t
GROUP BY rollup(a,b)

结果:
a1, b1, 10
a1, b2, 90
a1,   , 100

我需要:
a1, b1, 10, 100
a1, b2, 90, 100

怎么样?

最佳答案

该表模拟了您的情况:

SQL> create table t (a,b)
  2  as
  3   select 'a1', 'b1'
  4     from dual
  5  connect by level <= 10
  6    union all
  7   select 'a1', 'b2'
  8     from dual
  9  connect by level <= 90
 10  /

Table created.

您只有三行的结果会漏掉总计,因此有点不准确:rollup(a,b)会导致3行分组的结果包含4行。
SQL> select a
  2       , b
  3       , count(*)
  4    from t
  5   group by rollup(a,b)
  6  /

A  B    COUNT(*)
-- -- ----------
a1 b1         10
a1 b2         90
a1           100
             100

4 rows selected.

使用常规分组依据和顶部的分析功能,您可以实现所需的结果集:
SQL> select a
  2       , b
  3       , count(*)
  4       , sum(count(*)) over (partition by a)
  5    from t
  6   group by a
  7       , b
  8  /

A  B    COUNT(*) SUM(COUNT(*))OVER(PARTITIONBYA)
-- -- ---------- -------------------------------
a1 b2         90                             100
a1 b1         10                             100

2 rows selected.

问候,
抢。

关于sql - oracle sql组数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3856723/

10-11 16:08