因此,我有3个表: 支出 -记录费用 Directv- 记录电视频道的订阅付款 销售 -记录销售 ,我必须计算每月的营业额,销售总额,总费用和Directv
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
我想举个例子
turnover | Spending | sales | DirecTv | month | year 5500 | 3000 | 2000 | 50 | 10 |2018 1000 | 2000 | 500 | 0 | 11 |2018
我有一些问题要解决,我的查询是:
--to get total amount of sales select sum(sl.price) , month(sl.date) , year(sl.date) from sales sl GROUP by year(sl.date) , month(sl.date) --for directtv select sum(dv.amount) , month(dv.date) , year(dv.date) from directtv dv GROUP by year(dv.date) , month(dv.date) --for turnover SELECT sum(sl.quantity*sl.price) , month(sl.date) FROM sales sl GROUP by year(sl.date), month(sl.date)
但是如何按日期将所有SQL查询与分组进行分组 可以帮助我或给我任何提示呢?先感谢您
您可以使用合并表中的数据union all,然后进行汇总。
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) ;
这与查询中的内容不完全相同,但是鉴于您提供的数据,这才有意义。