gpt4 book ai didi

mysql - SQL 总和聚合包括 0

转载 作者:行者123 更新时间:2023-11-28 23:56:51 25 4
gpt4 key购买 nike

我有两张 table 。一个是包含员工信息的员工表,另一个表是员工的销售额。我正在尝试对一名员工一个月内的销售额总和进行分组,包括他/她销售额为零的月份。下面是表格中的一些值

员工表

number             name
1 Matt
2 Foggy
3 Karen
4 Wilson

销售额

employee_number           month          sale_number          sale_amount
1 January 2015 1 300
1 January 2015 2 50
1 February 2015 1 400
2 March 2015 1 300
3 January 2015 1 50

我能够使用以下查询编写获取月销售额的查询

选择 sum(sales.sale_amount), sales.employee_number, sales.month, sales.sale_number
来自 employee_number, month 的销售组;

现在,因为我还需要包括零在内的月份,我认为左外连接与不同的月份应该可以解决问题。但是,输出仍然包含与之前相同的输出,没有零或空值。左外连接不连接空值吗?

输出应该是这样的。
编号 名称 sale_amount sale_month
1 马特 350 2015 年 1 月
1 马特 400 2015 年 2 月
1 马特 0 2015 年 3 月
2 有雾 0 2015 年 1 月
2 2015 年 2 月 0 日
2 雾天 300 2015 年 3 月
等等。

最佳答案

左外部联接右手 表中缺失的行生成null 值。要显示所有月份,您需要切换表格的顺序:

from    months
cross join
employees
left outer join
sales
on sales.month = months.month
and employees.number = sales.employee_number

如果您缺少月份表,您可以从销售表中临时添加一个:

select  months.month
, employees.name
, sum(sale_amount) as sales
from (
select distinct month
from sales
) as months
cross join
employees
left outer join
sales
on sales.month = months.month
and employees.number = sales.employee_number
group by
months.month
, employees.name

Example at SQL Fiddle.

关于mysql - SQL 总和聚合包括 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31469821/

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