2 years ago

#57023

test-img

cdaveau

How can I simplify this GROUPING SETS query into a ROLLUP?

I'm trying to create a SELECT statement to calculate multiple levels of subtotals across two hierarchies. I have a Geo hierarchy which consists in region and department, and a Time hierarchy which consists in month and quarter.

At the moment, I have three tables which have the following structure:

CREATE TABLE Sales(
    Time_id Date NOT NULL,
    Geo_id CHAR(5) NOT NULL,
    Prod_id CHAR(6) NOT NULL,
    sales INT NOT NULL,
    PRIMARY KEY(Time_id, Geo_id, Prod_id)
);

CREATE TABLE Time(
    Time_id Date NOT NULL,
    month CHAR(2) NOT NULL,
    quarter CHAR(1) NOT NULL,
    year CHAR(4) NOT NULL,
    PRIMARY KEY(Time_id)
);

CREATE TABLE Geo(
   Geo_id CHAR(5) NOT NULL,
   city   VARCHAR(20) NOT NULL,
   dept   CHAR(2) NOT NULL,
   region CHAR(2) NOT NULL,
   PRIMARY KEY(Geo_id)
);

I wrote the following query that returns me the right values (63 rows):

SELECT
    Geo.region, Geo.dept, Time.month, Time.quarter, SUM(Sales.sales) AS sales
FROM
    Geo, Sales, Time
WHERE
    Sales.Time_id = Time.Time_id AND Sales.Geo_id = Geo.Geo_id
GROUP BY
    GROUPING SETS(
        (Geo.dept, Time.month),
        (Geo.dept, Time.quarter),
        (Geo.region, Time.month),
        (Geo.region, Time.quarter),
        Geo.dept,
        Geo.region,
        Time.month,
        Time.quarter,
        () -- thanks to @Larnu
    )

I find my query to be really repetitive and I think there is a better way of doing it using ROLLUP. Can anyone please help me to simplify it, as I'm relatively new to SQL analytics?

sql

sql-server

tsql

group-by

rollup

0 Answers

Your Answer

Accepted video resources