MySQL嵌套了多个连接和分组的和

时间:2017-03-17 20:12:06

标签: mysql

我有以下表格,我的结果总是不正确的

表1: product_category

f

表2: sold_items

  |  id |   title       |
  |  1  |   Electronics |
  |  2  |   Kitchen     |

表3: profit_table

| id | product_id | invoiceid | product_category_id | qty |
| 1  | 91         | 1001      | 1                   |  2  |
| 2  | 92         | 1001      | 1                   |  3  |
| 3  | 93         | 1002      | 2                   |  7  |
| 4  | 94         | 1002      | 2                   |  3  |
| 5  | 93         | 1003      | 2                   |  15  |

表4: product_log

| invoiceid | profit | cost   |
| 1001      | 200.00 | 980.00 |
| 1002      | 100.00 | 700.00 |
| 1003      | 350.00 | 900.00 |

我想求和(profit_table.profit),MONTH(product_log.tdate),SUM(sold_items.qty) 结果应该是product_category明智和月份,条件应该是YEAR(product_log.tdate)= 2017

示例 result_view

| id | product_id | qty | tdate       | invoiceid |
| 1  | 91         |  2  | 2017-01-10  | 1001      |
| 2  | 92         |  3  | 2017-01-10  | 1001      |
| 3  | 93         |  7  | 2017-02-10  | 1002      |
| 4  | 94         |  3  | 2017-02-10  | 1002      |
| 5  | 93         |  15 | 2017-03-10  | 1003      |

请建议我正确的查询

根据我的研究结果,

| title      | MONTH(product_log.tdate) | sum(profit) |SUM(sold_items.qty) |
| Electronics| 1                        | 200         | 5                  |
| Kitchen    | 2                        | 100         | 10                 |
| Kitchen    | 3                        | 350         | 15                 |

如果您想要回答

,这仍然不是一个正确的结果

3 个答案:

答案 0 :(得分:1)

以下书面查询应该有效。

您可以访问boolean indexing

psql -h localhost -p 5555 --username=mydb

答案 1 :(得分:0)

你应该使用SOME JOIN AND group by

select  
    product_category.title
  , MONTH(product_log.tdate)
  , sum(profit)
  , SUM(sold_items.qty) 
from product_category 
left join  sold_items on  sold_items.product_category_id =  product_category.id
left join product_log  on product_log.product_id = sold_items.product_id
left join profit_table on profit_table.invoiceid = product_log.invoiceid
group by  product_category.title, MONTH(product_log.tdate)

答案 2 :(得分:0)

您需要按产品和交易月份加入关键字和表格的表格。如下所示:

select pc.title, month(pl.tdate) as tmonth, sum(pt.profit) as month_profit, sum(si.qty) as month_qty
  from product_category pc
  left join sold_items si
    on si.product_category_id = pc.id
  left join profit_table pt
    on pt.invoice_id = si.invoice_id
  left join product_log pl
    on pl.product_id = si.product_id
   and pl.invoice_id = si.invoice_id
 group by pc.id, month(pl.tdate)
 where year(pl.tdate) = '2017';