0

我正在尝试为 mySql 中的每个组选择百分比值。

我试图在内存中进行,但要维护很多代码。如果我通过 SQL 来做,那就太好了。

我正在选择以下数据:

Gender,Category,Month,Year,NumberOfCustomers
'female','Feature Phones','1','2019','1000'
'male','Feature Phones','1','2019','10000'
'female','Smart Phones','1','2019','30000'
'male','Smart Phones','1','2019','200000'
'female','Feature Phones','2','2019','20000'
'male','Feature Phones','2','2019','15000'
'female','Smart Phones','2','2019','30000'
'male','Smart Phones','2','2019','150000'

使用查询:

SELECT gender, category, month, year, 
SUM(number_of_customers) AS numberOfCustomers
FROM customer_table 
WHERE brand_id IN (100) 
AND category in (1,2)        
AND month in (1,2) and year in (2019)
GROUP BY month, year, category, gender;

我想要的是每个月的客户百分比。前任:

Gender,Category,Month,Year,NumberOfCustomers,PercentageCustomersPerMonth
'female','Feature Phones','1','2019',5000,2.04
'male','Feature Phones','1','2019',10000,4.08
'female','Smart Phones','1','2019',30000,12.24
'male','Smart Phones','1','2019',200000,81.63
'female','Feature Phones','2','2019',20000,9.30
'male','Feature Phones','2','2019',15000,6.97
'female','Smart Phones','2','2019',30000,13.95
'male','Smart Phones','2','2019',150000,69.76

有没有办法轻松做到这一点?提前非常感谢。

4

2 回答 2

3

您可以使用窗口函数:

SELECT gender, category, month, year, 
       SUM(number_of_customers) AS numberOfCustomers,
       (SUM(number_of_customers) /
        SUM(SUM(number_of_customers)) OVER (PARTITION BY year, month)
       ) as month_ratio
FROM customer_table 
WHERE brand_id IN (100) AND
      category in (1,2) AND   
      month in (1, 2) AND
      year in (2019)
GROUP BY month, year, category, gender;
于 2019-10-20T02:50:59.780 回答
2

如果您无权访问窗口函数,您可以查看每月和每年的总客户表,并从中计算百分比JOINcustomer_table

SELECT c.*, 
       c.NumberOfCustomers / t.TotalCustomers * 100 AS PercentageCustomersPerMonth
FROM customer_table c
JOIN (SELECT Month, Year, SUM(NumberOfCustomers) AS TotalCustomers
      FROM customer_table
      GROUP BY Month, Year) t ON c.Month = t.Month AND c.Year = t.Year

输出:

Gender  Category        Month   Year    NumberOfCustomers   PercentageCustomersPerMonth
female  Feature Phones  1       2019    1000                0.4149
male    Feature Phones  1       2019    10000               4.1494
female  Smart Phones    1       2019    30000               12.4481
male    Smart Phones    1       2019    200000              82.9876
female  Feature Phones  2       2019    20000               9.3023
male    Feature Phones  2       2019    15000               6.9767
female  Smart Phones    2       2019    30000               13.9535
male    Smart Phones    2       2019    150000              69.7674

dbfiddle 上的演示

于 2019-10-20T02:56:01.680 回答