第五章 1-聚合函数aggregate functions--Mosh my SQL

这章我们会学习如何给数据写查询和进行汇总,比如按照客户或者每个地区进行报告销售,本章的内容,执行业务常见,很有用,特别在大型数据机构工作。

SQL自带一些函数,有一些叫聚合函数,如max(),min(),avg,(),sum(),count()

1,单个

select max(invoice_total)
from invoices

select max(invoice_total)
from invoices

2,多个。不管是单个还是多个查询,除了*返回的都是非空值,空值不计入

select
max(invoice_total) as highest,
min(invoice_total) as lowest,
avg(invoice_total) as average,
sum(invoice_total) as total,
count(invoice_total) as number_of_invoices,

count(invoice_date) as count_of_payment   #不是所有的都已经支付,只显示已支付的
count(*) as total_records     #显示所有记录数,空值也计入
from invoices

3,筛选2019年下半年的数据,这里我们发现total也随之改变。

select
select
max(invoice_total) as highest,
min(invoice_total) as lowest,
avg(invoice_total) as average,
sum(invoice_total*1.1) as total,
count(*) as total_records
from invoices
where invoice_date>'2019-07-01'

4,distinct 去重invoices里面有多条客户5号的记录,但我们现在只想看这里面有几个客户有记录,最终结果为3,

select
max(invoice_total) as highest,
min(invoice_total) as lowest,
avg(invoice_total) as average,
sum(invoice_total*1.1) as total,
count(distinct client_id) as total_records
from invoices
where invoice_date>'2019-07-01'

5,练习

对invoices表编写一段查询,得到如下

答案

select
'First half of 2019'as date_range,
sum(invoice_total) as total_sales,
sum(payment_total) as tatal_payments,
sum(invoice_total-payment_total) as what_we_expect
from invoices
where invoice_date between'2019-01-01'and '2019-06-30'
union
select
'second half of 2019'as date_range,
sum(invoice_total) as total_sales,
sum(payment_total) as tatal_payments,
sum(invoice_total-payment_total) as what_we_expect
from invoices
where invoice_date between'2019-07-01'and '2019-12-31'
union
select
'Total'as date_range,
sum(invoice_total) as total_sales,
sum(payment_total) as tatal_payments,
sum(invoice_total-payment_total) as what_we_expect
from invoices
where invoice_date between'2019-01-01'and '2019-12-31'

结果如下

为什么total_payments不一样呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值