简体   繁体   中英

Calculate the share of a certain criteria of the total per month

DB-Fiddle

CREATE TABLE sales (
    id int auto_increment primary key,
    country VARCHAR(255),
    sales_date DATE,
    sales_volume INT
);

INSERT INTO sales
(country, sales_date, sales_volume
)
VALUES 
("DE", "2020-01-03", "500"),
("DE", "2020-02-15", "700"),
("DE", "2020-03-27", "180"),
("NL", "2020-01-29", "320"),
("NL", "2020-02-03", "420"),
("NL", "2020-03-20", "420"),
("FR", "2020-01-18", "350"),
("FR", "2020-02-10", "180"),
("FR", "2020-03-30", "970");

Expected Result:

country     YEAR(sales_date)    MONTH(sales_date)   SUM(sales_volume)    sales_share
DE              2020                    1                 500               0.36
DE              2020                    2                 700               0.50
DE              2020                    3                 180               0.14
FR              2020                    1                 350               0.23
FR              2020                    2                 180               0.12
FR              2020                    3                 970               0.65
NL              2020                    1                 320               0.23
NL              2020                    2                 420               0.30
NL              2020                    3                 670               0.47

In the table above I have different countries and their corresponding sales .
Now, I want to calculate the sales_share of each country per month as you can see in the expected results.

SELECT 
country,
YEAR(sales_date),
MONTH(sales_date),
SUM(sales_volume)
FROM sales
GROUP BY 1,2,3;

How do I have to modify my query so it divides the sum per country by the total of all countries per month in order to get the sales_share ?

Use window functions:

SELECT country, YEAR(sales_date), MONTH(sales_date),
       SUM(sales_volume),
       SUM(sales_volume) / SUM(SUM(sales_volume)) OVER (PARTITION BY country) as ratio
FROM sales
GROUP BY 1,2,3;

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