如何使用来自其他 table 的数据在 SQL 中创建小计
How to create subtotal in SQL with data from other table
我正在尝试为不同邮政编码的销售额创建小计,因为发票没有邮政编码,我需要从客户那里获取它 table。
这是我的 sql,它将显示所有交易:
select c.name, c.zip, i.total, i.salestax from customer c, invoice i
where i.sdate >= '2019-09-01' and i.sdate <= '2019-09-30' and
c.accountnum=i.customernr
order by c.zip
我尝试将 SUM 添加到 total 和 salestax,但如果这样做,我会收到 SQL 错误。
如有任何帮助,我们将不胜感激。
谢谢,
KHJ
如果您想要按邮政编码汇总,那么这应该是您分组所依据的唯一键。然后你需要聚合函数:
select c.zip, sum(i.total), sum(i.salestax)
from customer c join
invoice i
on c.accountnum = i.customernr
where i.sdate >= '2019-09-01' and i.sdate <= '2019-09-30'
group by c.zip
order by c.zip
这是您的查询,您可以使用 sum() and group-by
获取结果
select c.name, c.zip, sum(i.total) as total, sum(i.salestax) as tax
from invoice i
inner join customer c on c.accountnum=i.customernr
group by c.zip, c.name
where i.sdate >= '2019-09-01' and i.sdate <= '2019-09-30'
order by c.zip
我正在尝试为不同邮政编码的销售额创建小计,因为发票没有邮政编码,我需要从客户那里获取它 table。
这是我的 sql,它将显示所有交易:
select c.name, c.zip, i.total, i.salestax from customer c, invoice i
where i.sdate >= '2019-09-01' and i.sdate <= '2019-09-30' and
c.accountnum=i.customernr
order by c.zip
我尝试将 SUM 添加到 total 和 salestax,但如果这样做,我会收到 SQL 错误。
如有任何帮助,我们将不胜感激。
谢谢, KHJ
如果您想要按邮政编码汇总,那么这应该是您分组所依据的唯一键。然后你需要聚合函数:
select c.zip, sum(i.total), sum(i.salestax)
from customer c join
invoice i
on c.accountnum = i.customernr
where i.sdate >= '2019-09-01' and i.sdate <= '2019-09-30'
group by c.zip
order by c.zip
这是您的查询,您可以使用 sum() and group-by
获取结果
select c.name, c.zip, sum(i.total) as total, sum(i.salestax) as tax
from invoice i
inner join customer c on c.accountnum=i.customernr
group by c.zip, c.name
where i.sdate >= '2019-09-01' and i.sdate <= '2019-09-30'
order by c.zip