0
我需要從兩個表的聯接中計算每個國家,城市,年份和月份的運行總數。所有數據的查詢都是這樣的:計算每個{country,city,year,month}組的運行總數
編輯:與TD_MONTH表的連接操作不是必需的。
SELECT costs.CITY,
costs.COUNTRY,
months.ID,
costs.ID_YEAR,
SUM (costs.AMOUNT) AMOUNT
FROM TH_COSTS costs
JOIN
TD_MONTH months
ON (costs.ID_MES = months.YEARMONTH)
GROUP BY costs.COUNTRY,
costs.CITY,
costs.ID_YEAR,
months.ID
ORDER BY costs.COUNTRY,
costs.CITY,
costs.ID_YEAR,
months.ID;
其中關於該網格的結果:上面我需要在未來的結果
+---------+--------+-------+------+-----------+
| Country | City | Month | Year | Amount |
+---------+--------+-------+------+-----------+
| Spain | Madrid | 4 | 2014 | 396061,7 |
| Spain | Madrid | 5 | 2014 | 315725,25 |
| Spain | Madrid | 6 | 2014 | 16390 |
| Spain | Madrid | 7 | 2014 | 85296 |
| Spain | Madrid | 8 | 2014 | 10443,25 |
| Spain | Madrid | 12 | 2014 | 17500 |
| Spain | Madrid | 1 | 2015 | 353566 |
| Spain | Madrid | 2 | 2015 | 382729 |
| Spain | Madrid | 3 | 2015 | 261026 |
| Spain | Madrid | 4 | 2015 | 304258 |
| Spain | Madrid | 5 | 2015 | 259893 |
| Spain | Madrid | 6 | 2015 | 217296 |
| Spain | Madrid | 7 | 2015 | 461769 |
| Spain | Madrid | 8 | 2015 | 456990,5 |
| Spain | Madrid | 9 | 2015 | 219020 |
| Spain | Madrid | 10 | 2015 | 242796 |
| Spain | Madrid | 11 | 2015 | 134197 |
| Spain | Madrid | 12 | 2015 | 91901,9 |
+---------+--------+-------+------+-----------+
而且從一個:
+---------+--------+-------+------+-----------+
| Country | City | Month | Year | Amount |
+---------+--------+-------+------+-----------+
| Spain | Madrid | 1 | 2014 | 0 |
| Spain | Madrid | 2 | 2014 | 0 |
| Spain | Madrid | 3 | 2014 | 0 |
| Spain | Madrid | 4 | 2014 | 396061,7 |
| Spain | Madrid | 5 | 2014 | 711786,95 |
| Spain | Madrid | 6 | 2014 | 728176,95 |
| Spain | Madrid | 7 | 2014 | 813472,95 |
| Spain | Madrid | 8 | 2014 | 823916,2 |
| Spain | Madrid | 9 | 2014 | 841416,2 |
| Spain | Madrid | 10 | 2014 | 1194982,2 |
| Spain | Madrid | 11 | 2014 | 1577711,2 |
| Spain | Madrid | 12 | 2014 | 1595211,2 |
| Spain | Madrid | 1 | 2015 | 353566 |
| Spain | Madrid | 2 | 2015 | 736295 |
| Spain | Madrid | 3 | 2015 | 997321 |
| Spain | Madrid | 4 | 2015 | 1301579 |
| Spain | Madrid | 5 | 2015 | 1561472 |
| Spain | Madrid | 6 | 2015 | 1778768 |
| Spain | Madrid | 7 | 2015 | 2240537 |
| Spain | Madrid | 8 | 2015 | 2697527,5 |
| Spain | Madrid | 9 | 2015 | 2916547,5 |
| Spain | Madrid | 10 | 2015 | 3159343,5 |
| Spain | Madrid | 11 | 2015 | 3293540,5 |
| Spain | Madrid | 12 | 2015 | 3385442,4 |
+---------+--------+-------+------+-----------+
編輯:在起始表格字段:
+----------+----------+--------+--------+--------+--------+-----------+---------+------+
| AMOUNT_1 | AMOUNT_2 | STREET | CITY 1 | MONTH | CITY 2 | CONTINENT | COUNTRY | YEAR |
+----------+----------+--------+--------+--------+--------+-----------+---------+------+
首先想到的是使用四個嵌套循環,但這是一個非常耗時的解決方案。
任何想法?
它返回重複行,我怎麼能刪除? –
你有什麼結果?它返回的行數與起始表完全相同,每行的總計行數爲 – Aleksej
我編輯了主要帖子以顯示剩餘字段 –