使用SQL查询获取特定类别和进一步分支的子类别的计数

编程入门 行业动态 更新时间:2024-10-18 10:27:59
本文介绍了使用SQL查询获取特定类别和进一步分支的子类别的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我希望使用sql查询从数据库中获取摘要报告,以显示按类别对它们进行分组的计数,还可以进一步显示每个类别下的分组子类别计数. 例如在下面的快照中:我想总结一下我的男性和女性雇员数量数据,还要显示每种性别下不同雇员职位的数量.预先感谢.

I am looking to get a summary report from my database using sql query to show their count grouped them by category but also to further show the grouped subcategory count under each category. e.g. in attached snapshot below: I want to summarize my data for number of male and female employees but also to show under each gender the count of different employee position. Thanks in advance.

推荐答案

假定表结构如下:

id -- primary key gender -- 'Male', 'Female' position -- 'Senior Manager', 'Manager', 'Employee'

您可以UNION ALL一系列聚合查询以产生预期的结果.

You could UNION ALL a series of aggregated queries to produce the expected results.

SELECT cat, cnt FROM ( SELECT 1 rn, 'Male' cat, SUM(gender = 'Male') cnt FROM mytable UNION ALL SELECT 2, 'Senior Manager', SUM(gender = 'Male' and position = 'Senior Manager') FROM mytable UNION ALL SELECT 3, 'Manager', SUM(gender = 'Male' and position = 'Manager') FROM mytable UNION ALL SELECT 4, 'Employee', SUM(gender = 'Male' and position = 'Employee') FROM mytable UNION ALL SELECT 5, 'Female', SUM(gender = 'Female') FROM mytable UNION ALL SELECT 6, 'Senior Manager', SUM(gender = 'Female' and position = 'Senior Manager') FROM mytable UNION ALL SELECT 7, 'Manager', SUM(gender = 'Female' and position = 'Manager') FROM mytable UNION ALL SELECT 8, 'Employee', SUM(gender = 'Female' and position = 'Employee') FROM mytable ) ORDER BY rn

附加列rn用于在结果集中按顺序保留记录.

Additional column rn is there to keep the records in order in the resultset.

更多推荐

使用SQL查询获取特定类别和进一步分支的子类别的计数

本文发布于:2023-11-22 05:57:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616225.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子类   分支   类别   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!