简体   繁体   中英

Subtotal levels for ROLLUP on four columns in Oracle SQL

I'm trying to construct an Oracle SQL query using the ROLLUP operator. The query needs to summarize sales by year, quarter, store state, and store city over two years, with the result including subtotals for the two hierarchical dimensions of year/quarter and state/city. Here's my attempt thus far:

SELECT storestate, storecity, calyear, calquarter, SUM(sales) AS Sales
FROM store_dim, time_dim, sales_fact
WHERE sales_fact.storeid = store_dim.storeid
    AND sales_fact.timenum = time_dim.timenum
    AND (calyear BETWEEN 2011 AND 2012)
GROUP BY ROLLUP(calyear, calquarter, storestate, storecity);

I'm trying to figure out if, as it's currently written, the query is showing subtotals for the two hierarchies I'm looking for, rather than treating them as one big one. Attempting to map out the subtotal levels by hand didn't help, and I haven't been able to find any examples of a single ROLLUP with four columns from two dimensions, or an example of two ROLLUP operators in a single GROUP BY clause, like below:

GROUP BY ROLLUP(calyear, cal quarter), ROLLUP(storestate, storecity)

A breakdown of the subtotal levels produced by the two GROUP BY clauses would be hugely helpful.

Edit: I'm specifically to use ROLLUP here. GROUPING SETS would generally be the first choice for this kind of query otherwise.

Use grouping sets . . . and proper, explicit, standard join syntax:

select s.storestate, s.storecity, t.calyear, t.calquarter,
       sum(sf.sales) AS Sales
from sales_fact sf join
     store_dim s
     on s.storeid = sf.storeid join
     time_dim t 
     on sf.timenum = t.timenum
where calyear between 2011 and 2012
group by grouping sets ( (calyear, calquarter, storestate, storecity),
                         (calyear, calquarter), (storestate, storecity)
                       );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM