gpt4 book ai didi

mysql - 按日期月份分组多个表

转载 作者:行者123 更新时间:2023-11-29 10:00:18 25 4
gpt4 key购买 nike

所以我有 3 个表,名为:
支出 - 记录支出
Directv - 记录电视 channel 的订阅付款
销售额 - 记录销售额
我必须计算每个月的营业额、销售总额、总费用和 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组合表中的数据,然后进行聚合。

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

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) ;

这并不完全是您查询中的内容,但考虑到您提供的数据,它是有意义的。

关于mysql - 按日期月份分组多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53140514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com