select 组=(case when 班级 = (select top 1 班级 from tb where 组=a. 组) then a. 组 else '' end), 班级, 分数 from tb a
declare @a table(组 varchar(10),班级 int,分数 int) insert @a select '甲', 101 , 14 union all select '乙', 140, 15 union all select '乙', 141 , 18 union all select '丙', 230 , 20 union all select '丙', 231 , 50 union all select '丙', 232 , 60select 组=(case when 班级 = (select top 1 班级 from @a where 组=a. 组) then a. 组 else '' end), 班级, 分数 from @a a运行后就得楼主的结果
我这边组,班级,数分是一张表的,总是提示 "在选择列表中无效,因为该列未包含在聚合函数中,并且没有 GROUP BY 子句。"
我的示例数据也是一张表啊 你把那个查询语句的@a 换成你个表名就可以了 注意: from @a a 换成后的结果是: from 表名 a 后面那个a 是你表的别名,不要删除掉
select 组=(case when not exists(select 1 from @a where 组=a.组 and 班级<a.班级) then 组 else '' end),班级,分数 from @a a
我可能刚才没说清楚,我表中可能班级有两个的话,统计时也要把它的分数加相成一个 如: declare @a table(组 varchar(10),班级 int,分数 int) insert @a select '甲', 101 , 14 union all select '甲', 101 , 60 union all select '乙', 140, 15 union all select '乙', 140, 30 union all select '乙', 141 , 18 union all select '丙', 230 , 20 union all select '丙', 231 , 50 union all select '丙', 232 , 60
是这样的,关键在于分组,我测试过没问题。 create table ta(组 varchar(10),班级 int,分数 int) insert ta select '甲', 101 , 14 union all select '乙', 140, 15 union all select '乙', 141 , 18 union all select '丙', 230 , 20 union all select '丙', 231 , 50 union all select '丙', 232 , 60select 组=( case when 班级 = (select top 1 班级 from ta where 组=a. 组) then a. 组 else '' end ),班级,分数 from ta a group by 组,班级,分数
组=(case
when 班级 = (select top 1 班级 from tb where 组=a. 组)
then a. 组
else
''
end),
班级,
分数
from tb a
insert @a
select '甲', 101 , 14 union all
select '乙', 140, 15 union all
select '乙', 141 , 18 union all
select '丙', 230 , 20 union all
select '丙', 231 , 50 union all
select '丙', 232 , 60select
组=(case
when 班级 = (select top 1 班级 from @a where 组=a. 组)
then a. 组
else
''
end),
班级,
分数
from @a a运行后就得楼主的结果
注意:
from @a a 换成后的结果是: from 表名 a
后面那个a 是你表的别名,不要删除掉
如:
declare @a table(组 varchar(10),班级 int,分数 int)
insert @a
select '甲', 101 , 14 union all
select '甲', 101 , 60 union all
select '乙', 140, 15 union all
select '乙', 140, 30 union all
select '乙', 141 , 18 union all
select '丙', 230 , 20 union all
select '丙', 231 , 50 union all
select '丙', 232 , 60
create table ta(组 varchar(10),班级 int,分数 int)
insert ta
select '甲', 101 , 14 union all
select '乙', 140, 15 union all
select '乙', 141 , 18 union all
select '丙', 230 , 20 union all
select '丙', 231 , 50 union all
select '丙', 232 , 60select 组=(
case when 班级 = (select top 1 班级 from ta where 组=a. 组)
then a. 组
else
''
end
),班级,分数 from ta a
group by 组,班级,分数