SQL根据不同类型分类统计(类型在表中出现的次数)

//这里模拟的是根据人员分组统计,想了解每个人职员最近哪种工作做得比较多
//还可以根据时间范围查询,条件可以根据个人需求来修改
select us.u_name,
 sum(case when tb.t_name = '新增需求' then 1 else 0 end) as '新增需求',
 sum(case when tb.t_name = '数据维护' then 1 else 0 end) as '数据维护',
 sum(case when tb.t_name = '设备维护' then 1 else 0 end) as '设备维护',
 sum(case when tb.t_name = '日常工作' then 1 else 0 end) as '日常工作',
 sum(case when tb.t_name = '常用软件安装' then 1 else 0 end) as '常用软件安装',
 sum(case when tb.t_name = '网络维护' then 1 else 0 end) as '网络维护',
 sum(case when tb.t_name = '其他需求' then 1 else 0 end) as '其他需求',
 sum(case when tb.t_name = '系统维护' then 1 else 0 end) as '系统维护',
 sum(case when tb.t_name = '权限维护' then 1 else 0 end) as '权限维护',
 sum(case when tb.t_name = '程式维护' then 1 else 0 end) as '程式维护',
 sum(case when tb.t_name = '程序需求' then 1 else 0 end) as '程序需求'
from sys_user us 
left join type_body tb 
on us.id = tb.id 
GROUP BY us.u_name;

//不带参数就统计出现次数,不需要看是谁做了多少事,就想看每个类型总共出现的次数
select
 sum(case when tb.t_name = '新增需求' then 1 else 0 end) as '新增需求',
 sum(case when tb.t_name = '数据维护' then 1 else 0 end) as '数据维护',
 sum(case when tb.t_name = '设备维护' then 1 else 0 end) as '设备维护',
 sum(case when tb.t_name = '日常工作' then 1 else 0 end) as '日常工作',
 sum(case when tb.t_name = '常用软件安装' then 1 else 0 end) as '常用软件安装',
 sum(case when tb.t_name = '网络维护' then 1 else 0 end) as '网络维护',
 sum(case when tb.t_name = '其他需求' then 1 else 0 end) as '其他需求',
 sum(case when tb.t_name = '系统维护' then 1 else 0 end) as '系统维护',
 sum(case when tb.t_name = '权限维护' then 1 else 0 end) as '权限维护',
 sum(case when tb.t_name = '程式维护' then 1 else 0 end) as '程式维护',
 sum(case when tb.t_name = '程序需求' then 1 else 0 end) as '程序需求'
from type_body tb 

 

### 如何在 SQL 中进行分类统计查询分组汇总 #### 使用 GROUP BY 进行基本分组操作 为了实现有效的数据分析,`GROUP BY` 子句用于将具有相同值的记录组合在一起。这使得可以针对每一组执行聚合运算,从而简化复杂的数据集处理过程[^1]。 例如,在一个名为 `sales` 的中按地区和地区内的城市来查看销售总额: ```sql SELECT region, city, SUM(sales_amount) AS total_sales FROM sales GROUP BY region, city; ``` 此语句会返回每个城市的总销售额,并按照区域和城市两个层次进行了分组。 #### 应用 HAVING 来过滤分组后的结果 除了简单的分组外,还可以利用 `HAVING` 子句进一步筛选符合条件的分组。这对于找出特定条件下的数据非常有用,比如找到至少有两个同名学生的名单[^4]: ```sql SELECT name, COUNT(*) as num_students FROM students GROUP BY name HAVING COUNT(name) >= 2; ``` 这段代码能够识别出哪些名字出现了两次及以上,并显示这些名字及其出现次数。 #### 结合多种聚合函数增强分析能力 SQL 提供了一系列内置的聚合函数如 `COUNT()`, `SUM()`, `AVG()`, `MAX()` 和 `MIN()` 等,可用于完成不同类型统计任务[^3]。下面的例子展示了如何在一个订单格里获取每种商品的不同属性信息: ```sql SELECT product_id, COUNT(order_id) AS order_count, SUM(quantity) AS total_quantity_sold, AVG(price_per_unit * quantity) AS avg_order_value, MAX(price_per_unit) AS max_price_paid, MIN(price_per_unit) AS min_price_paid FROM orders GROUP BY product_id; ``` 上述查询不仅给出了各产品的订购数量、售出总量以及平均交易价值,还提供了最高售价与最低售价之间的对比情况。 通过以上几种方式的应用,可以在 SQL 中高效地实施分类统计查询并进行深入的数据挖掘工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值