0

毎月利益を上げている都市のすべての地区をリストする必要があります。

商品のカウント値をサブクエリで月と結びつける方法がわかりません。

誰か手を貸してくれませんか?

SELECT 
       districts.id,
       districts.name,
       mmonth.m10
FROM districts
INNER JOIN
  (SELECT 
       SUM(product_order.price_of_day * product_order.amount) AS m10
   FROM product_order
   INNER JOIN orders ON product_order.order_id = orders.id
   WHERE MONTH(orders.date_time) = 10 ) mmonth
INNER JOIN cities ON cities.id = districts.city_id
WHERE cities.id = 2;

http://sqlfiddle.com/#!2/8fb34/4

私が必要なものを見てください。

| id |     name   | m10 | m11 | m12 |
------------------------------------
|  3 | district 3 | 730 | 360 | 453 |
------------------------------------
|  4 | district 4 | 730 | 250 | 856 |
-------------------------------------

このような月をどのように合計しますか?

| id |     name   | m10 | m11 | m12 | total |
---------------------------------------------
|  3 | district 3 | 730 | 360 | 453 | 1543  |
---------------------------------------------
|  4 | district 4 | 730 | 250 | 856 | 1836  |
---------------------------------------------
4

2 に答える 2

1

編集:

これはそれを行う必要があります:

SELECT 
       districts.id,
       districts.name,
       SUM(IF(MONTH(orders.date_time) = 10, product_order.price_of_day * product_order.amount, 0)) AS m10,
       SUM(IF(MONTH(orders.date_time) = 11, product_order.price_of_day * product_order.amount, 0)) AS m11,
       SUM(IF(MONTH(orders.date_time) = 12, product_order.price_of_day * product_order.amount, 0)) AS m12,
       SUM(product_order.price_of_day * product_order.amount) AS total
FROM cities
LEFT JOIN districts ON cities.id = districts.city_id
LEFT JOIN orders ON orders.district_id = districts.id
LEFT JOIN product_order ON product_order.order_id = orders.id
WHERE cities.id = 2
GROUP BY districts.id;
于 2013-11-07T16:18:50.723 に答える