按日期月份多个表分组

时间:2018-11-04 11:51:55

标签: mysql sql

所以我有3个表:
支出-记录支出
Directv -记录电视频道的订阅付款
销售-记录销售
而且我必须计算每个月的营业额,总销售额,总费用和Directv

let hi = "value"

我想举个例子

dune utop

我有一些问题要解决, 我的查询:

    Spending
    id|Amount|dateSpd
    1 |2000  |2018-10-05
    3 |3000  |2018-11-06

    Directv
    id|Amount|dateTv
    1 |50    |2018-10-05

    Sales
    id|customer|quantity|price|dateSales
    1 |Marc    |2       |500  |2018-10-05
    2 |Kevin   |3       |1500 |2018-10-05
    5 |Angel   |2       |500  |2018-11-07

但是如何将所有带有联接的SQL查询按日期分组
有人可以帮助我或给我任何提示吗?预先谢谢你

1 个答案:

答案 0 :(得分:1)

您可以使用union all合并表中的数据,然后进行汇总。

我怀疑您想要这样的东西:

select year(dte), month(dte),
       sum(spending) as spending, sum(directtv) as directtv,
       sum(price*quantity) as turnover
from ((select datesp as dte, amount as spending, 0 as directtv, 0 as price, 0 as quantity
       from spending
      ) union all
      (select datetv as dte, 0 as spending, amount as directtv, 0 as price, 0 as quantity
       from directtv
      ) union all
      (select datesales as dte, 0 as spending, 0 as directtv, price, quantity
       from sales
      )
     ) x
group by year(dte), month(dte) ;

这并不是您查询中的确切内容,但鉴于您提供的数据,这才有意义。