Pular para o conteúdo

Fóruns SQL e PL/SQL Sumarizar o resultado de um select Sumarizar o resultado de um select

#94512
fsitja
Participante

    [quote=”burga”:1c49agdh]isso deve resolver…
    select * from (select x1,x2,x3,n1,n2 from teste_agrupamento
    union all
    select null, null, null, sum(n1), sum(n2) from teste_agrupamento)
    order by 4;

    edit:

    atrasei… 😆 [/quote]

    hehe, é apenas outra forma de pedir a mesma coisa pro Oracle 😉

    No link abaixo dos Docs:
    http://download.oracle.com/docs/cd/E118 … #DWHSG8631

    GROUPING SETS Syntax

    GROUPING SETS syntax lets you define multiple groupings in the same query. GROUP BY computes all the groupings specified and combines them with “UNION ALL”. For example, consider the following statement:

    GROUP BY GROUPING sets (channel_desc, calendar_month_desc, country_id )

    This statement is equivalent to:

    GROUP BY channel_desc “UNION ALL”
    GROUP BY calendar_month_desc “UNION ALL” GROUP BY country_id

    A diferença é que o Grouping Sets vai fazer um único scan na tabela, sendo um pouco mais eficiente.

    Quanto ao uso de rollup, pode ser feito também para chegar no resultado, mas, de novo, o desempenho vai ser inferior pois ele vai calcular os subtotais ao longo de todas dimensões para depois descartá-los no having:

    SQL> SELECT x1, x2, x3, SUM(n1), SUM(n2)
    2 FROM teste_agrupamento
    3 GROUP BY ROLLUP (x1, x2, x3)
    4 HAVING GROUPING(x1) + GROUPING(x2) + GROUPING(x3) = 0
    5 OR GROUPING(x1) + GROUPING(x2) + GROUPING(x3) = 3;

    X1 X2 X3 SUM(N1) SUM(N2)


    A T D 2 3
    A Y A 1 2
    B E U 3 4
    C D J 4 6
    E A W 5 7
    15 22

    6 rows selected

    edit: o fórum dá erro quando tento postar as palavras “UNION ALL” sem as aspas.