您的位置:首页 > 数据库

SQL学习记录10:分组与聚集

2015-07-20 21:32 405 查看

分组

select cust_type_cd , count(*) how_many
from customer
group by cust_type_cd
having how_many > 10


聚集

隐式或显示分组

聚集函数

Min()

Avg()

Sum()

Count()

select max(avail_balance) max_balance,
min(avail_balance) max_balance,
avg(avail_balance) max_balance,
sum(avail_balance) max_balance,
count(*) num_accounts
from account
group by product_cd




对独立值计数

计算不同id的个数用到了distinct

select  count(distinct open_emp_id)
from account


使用表达式

select  max(pending_balance - avail_balance) max_data
from account


在进行计算时候要注意null值所带来的影响, count(*)与sum 可能不同

多列分组

select product_cd, open_branch_id,
sum(avail_balance) tot_balance
from account
group by product_cd, open_branch_id
order by open_branch_id desc




利用表达式分组

select extract(year from start_date) year,
count(*) how_many
from employee
group by extract(year from start_date)




extract 用来输出日期中的年份

警告

当在包含group by 字句的查询时增加过滤条件时候, 应该考虑是对原始数据过滤还是对group后的数据过滤。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: