用于计算值在多列中出现的SQL查询

cnjp1d6j  于 2022-09-18  发布在  Java
关注(0)|答案(2)|浏览(127)

下面是学生和他/她学习不同学科的两种兴趣的输入表。

学生|Int1|Int2
-|-|
1|DS|网络
2|操作系统|DS
3|DS|操作系统
4|网络|数据库
5|操作系统|网络
6|数据库|DS
7|网络|操作系统
8|数据库|操作系统

需要找到感兴趣的领域和对它感兴趣的学生数量。

输出应为
兴趣|学生总数

DS|4
操作系统|5
数据库|3
网络|4

uajslkp6

uajslkp61#

首先,我将2结果连接到一个临时表中,并按临时表进行计数。

;with ETA(ref,count1) as 
(select Int1, count(Int1) from [yourtable] group by Int1
union all
select Int2, count(Int2) from [yourtable] group by Int2)
select count1, count(count1) from ETA group by count1
waxmsbnn

waxmsbnn2#

您可以查询这两列中的数据,然后使用UNION ALL将它们放在一起,最后使用GROUP BY统计数据

SELECT count(c.student) as cnt, c.inte
FROM
(
SELECT `int1` as inte,student FROM course 
union all
SELECT `int2` as inte,student FROM course 
) c
GROUP BY c.inte
ORDER BY c.inte

DB Fiddle Demo

测试结果
Cnt|inte

3|数据库
4|DS
4|网络
5|操作系统

相关问题