sql 查询之分段统计

sql 分段统计

sql 分段统计数量,总数等

 


前言

使用sql 快速的进行分段统计

 

一、sql 分段统计长度

根据不同的管径统计总的长度

如:

sql 查询之分段统计_第1张图片

sql 执行语句:

select case when PIPECALIBER between 0 and 300 then '0-300'
when PIPECALIBER between 300 and 600 then '300-600'
when PIPECALIBER between 600 and 900 then '600-900'
when PIPECALIBER between 900 and 1200 then '900-1200'
when PIPECALIBER between 1200 and 1600 then '1200-1600'
else '其它' end as 管径, sum(STATISTIC_LEN) as 长度 from test.linepipe group by case when PIPECALIBER between 0 and 300 then '0-300'
when PIPECALIBER between 300 and 600 then '300-600'
when PIPECALIBER between 600 and 900 then '600-900'
when PIPECALIBER between 900 and 1200 then '900-1200'
when PIPECALIBER between 1200 and 1600 then '1200-1600'
else '其它' end

统计结果:

sql 查询之分段统计_第2张图片

二、分段统计数量

1.sql 语句

select case when PIPECALIBER between 0 and 300 then '0-300'
when PIPECALIBER between 300 and 600 then '300-600'
when PIPECALIBER between 600 and 900 then '600-900'
when PIPECALIBER between 900 and 1200 then '900-1200'
when PIPECALIBER between 1200 and 1600 then '1200-1600'
else '其它' end as 管径, count(PIPECALIBER) as 长度 from test.linepipe group by case when PIPECALIBER between 0 and 300 then '0-300'
when PIPECALIBER between 300 and 600 then '300-600'
when PIPECALIBER between 600 and 900 then '600-900'
when PIPECALIBER between 900 and 1200 then '900-1200'
when PIPECALIBER between 1200 and 1600 then '1200-1600'
else '其它' end
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import warnings warnings.filterwarnings('ignore') import ssl ssl._create_default_https_context = ssl._create_unverified_context 

2.统计结果

sql 查询之分段统计_第3张图片

另外一种方式:

select sum(case when PIPECALIBER between 0 and 300 then 1 else 0 end) as '0-300',
sum(case when PIPECALIBER between 300 and 600 then 1 else 0 end) as '300-600',
sum(case when PIPECALIBER between 600 and 900 then 1 else 0 end) as '600-900',
sum(case when PIPECALIBER between 900 and 1200 then 1 else 0 end) as '900-1200',
sum(case when PIPECALIBER between 1200 and 1600 then 1 else 0 end) as '1200-1600'
from test.linepipe

统计结果

sql 查询之分段统计_第4张图片

SQL的世界中CASE语句相当于if -----else  语句

Case具有两种格式。简单Case函数和Case搜索函数

1. 简单Case函数
CASE sex
WHEN '1' THEN '男'
WHEN '2' THEN '女'
ELSE '其他' END
2. Case搜索函数
CASE WHEN sex = '1' THEN '男'
WHEN sex = '2' THEN '女'
ELSE '其他' END
这两种方式,可以实现相同的功能。

 

三、分类统计数量

 

select MATERIAL '材质', count(MATERIAL) '数量' from test.linepipe l group by l.MATERIAL

sql 查询之分段统计_第5张图片

 

 


总结

以上是sql 统计的常用方法,结合自己的需要总结,如有不足之处,望读者批评指正,谢谢

你可能感兴趣的:(sql学习,sql)