2020-12-29 22:33:26
1、创建测试表,
create table test_stu(id number, u_name varchar2(20), subject varchar2(20));
create table test_subj(id number, subject varchar2(20));

2、插入测试数据
insert into test_stu values(1,'张三','英语');
insert into test_stu values(2,'李四','德语');
insert into test_stu values(3,'
insert into test_stu values(4,'小明','英语');
insert into test_stu values(5,'小狗','法语');
insert into test_subj values(1,'英语');
insert into test_subj values(2,'德语');
insert into test_subj values(3,'日语');
insert into test_subj values(4,'法语');

3、查询表中所有记录数,select t.*, rowid from test_subj t,

4、编写sql,统计test_subj总记录数,及每个科目选修学生数;
select count(distinct t.id) as "小计",
count(case when subject='英语' then 1 end) as "英语",
count(case when subject='德语' then 1 end) as "德语",
count(case when subject='日语' then 1 end) as "日语"
from (select t.*
from test_subj t, test_stu b
where t.subject = b.subject) t

2023-03-14 19:53:42
sqlserver为例
创建表及插入数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
然后需要创建一个视图
1 2 3 4 5 |
执行语句
1 2 3 4 5 6 7 |
结果截图

你结果里为什么会少呢?
这个主要是动态显示才这么复杂,比如你在科目表里再加个阿拉伯语,用这个也没问题,否则用case when的写法会比较有局限性
2021-05-03 07:43:32
create table 姓名表(id int,u_name varchar(10),subject varchar(10))create table 科目表(id int,s_name varchar(10))insert into 姓名表 values (1,'张三','英语')insert into 姓名表 values (2,'李四','德语')insert into 姓名表 values (3,'王五','日语')insert into 姓名表 values (4,'小明','英语')insert into 姓名表 values (5,'小狗','法语')insert into 科目表 values (1,'英语')insert into 科目表 values(2,'德语')insert into 科目表 values(3,'日语')insert into 科目表 values(4,'法语')create view v_subjectasselect a.s_name,SUM(case when a.s_name=b.subject then 1 else 0 end) countsfrom 科目表 a left join 姓名表 b on a.s_name=b.subjectgroup by a.s_namedeclare @sql varchar(4000)set @sql = 'select sum(counts) as 合计'select @sql = @sql + ',sum(isnull(case [s_name] when '''+[s_name]+''' then [counts] end,0)) as ['+[s_name]+']'from (select distinct [s_name] from v_subject) as aselect @sql = @sql+' from [v_subject]'exec (@sql)