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

result:

a1, b1, 10
a1, b2, 90
a1,   , 100

i need:

a1, b1, 10, 100
a1, b2, 90, 100

how?

2 Answers 2

6

This table simulates your situation:

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.

Your result with only three rows misses the grand total, so that's a little inaccurate: rollup(a,b) results in 3 grouping sets with 4 rows.

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.

With a regular group by and an analytic function on top, you can achieve your desired result set:

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.

Regards, Rob.

0
1

Use:

  SELECT t.a,
         t.b,
         COUNT(*),
         (SELECT COUNT(*)
            FROM YOUR_TABLE
        GROUP BY t.a) 
    FROM YOUR_TABLE t
GROUP BY t.a, t.b
2
  • This accesses YOUR_TABLE twice, which is not necessary. Oct 4, 2010 at 16:35
  • @Rob van Wijk: I agree that it accesses the table twice, but there's no alternative if analytics aren't supported (pre 8i)
    – OMG Ponies
    Oct 4, 2010 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.