日期:2014-05-17  浏览次数:20729 次

SQL 班级分组查询
本帖最后由 jzkaixin 于 2012-11-27 08:34:47 编辑
ID 姓名    性别      年龄     班级
1       张三     1       18       1
2       李四     1       18       1
3       赵武     1       19       1
4       小明     1       17       1
5       刘涛     1       18       2
6       小红     2       17       2
7       小芳     2       18       2
8       小红     2       18       2
9       张三     1       18       1
10      李四     1       17       1


班级表
我想以班级分组显示  
select 姓名,性别,年龄 From Kx001 GROUP BY 班级

如何实现?

select 姓名,性别,年龄 From Kx001 GROUP BY 班级,姓名,性别,年龄

如果这样的话 有一个问题 那就是 同名的同学只会显示出来一个 



比如 张三  名字 年龄 性别一样 这样就只显示一个张三了!
------解决方案--------------------
不太懂楼主的意思,难道是要下面的结果? 但是这个结果个人觉得没什么意义

--测试数据
if OBJECT_ID('student') is not null drop table student
create table student(ID int identity(1,1),姓名 nvarchar(20),性别 int,年龄 int,班级 int)
go
insert into student(姓名,性别,年龄,班级)
select '张三',1,18,1 union all
select '李四',1,18,1 union all
select '赵武',1,19,1 union all
select '小明',1,17,1 union all
select '刘涛',1,18,2 union all
select '小红',2,17,2 union all
select '小芳',2,18,2 union all
select '小红',2,18,2 union all
select '张三',1,18,1 union all
select '李四',1,17,1
--查询
select 姓名,性别,年龄 From student GROUP BY 班级,姓名,性别,年龄
union all
select 姓名,性别,年龄 From student GROUP BY 班级,姓名,性别,年龄 having COUNT(1)>1

/**
姓名                   性别          年龄
-------------------- ----------- -----------
李四                   1           17
李四