Вычислить суммирование по нескольким аспектам - PullRequest
0 голосов
/ 14 июля 2020

У меня есть таблица базы данных, похожая на следующую картинку. Каждый раз, когда сообщается об излучении, в таблицу вставляется строка. Столбец total - это просто добавление столбцов CO и CO2. Для любого города на определенную дату может быть несколько строк. В следующей таблице представлены данные только для двух дат и трех разных городов.

Sample database

For each date, I need to compute totals for CO, CO2, and total columns for each city, then calculate the subtotal of those cities for that date. Finally, combine those subtotals into a grand total. The following picture represents the result I am trying to achieve,

Expected result

In addition to that, I also need to keep a couple of filters such as result for a certain date range or a certain country, etc. I am planning to query rows and loop over them to compute the summations at the PHP end. This approach is questionable as it does not seem very efficient for a large volume of data. I was wondering if there is any efficient way of doing this type of computation, maybe using complex GROUP BY or temporary table/view at the MySQL end. Please suggest any better way to do it for a table that may grow up to a few millions of rows. Let me also include an array representation of the sample data for convenience,

$sample = [
    ['id', 'date', 'country', 'city', 'CO', 'CO2', 'total'],
    [1, '2020-07-13', 'US', 'Scarsdale', 5, 10, 15],
    [2, '2020-07-13', 'US', 'Scarsdale', 10, 10, 20],
    [3, '2020-07-13', 'US', 'SF', 5, 15, 20],
    [4, '2020-07-13', 'US', 'SF', 15, 25, 40],
    [5, '2020-07-13', 'UK', 'London', 10, 15, 25],
    [6, '2020-07-12', 'UK', 'London', 10, 20, 30],
    [7, '2020-07-12', 'UK', 'London', 5, 5, 10],
    [8, '2020-07-12', 'US', 'SF', 10, 20, 30],
    [9, '2020-07-12', 'US', 'Scarsdale', 5, 5, 10],
];

Заранее спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...