我有一个表“学生”,现在我想查询结果与第二个表相同。一组必须有2名学生。

时间:2010-03-02 07:26:22

标签: sql

我有一个表Student,现在我想查询结果和第二个表一样。一组必须有2名学生。

Student ID    Name    Gender    Group
1             A       M         A1
2             B       F         A1
3             C       M         A2
4             D       M         A2
5             E       F         A3
6             F       F         A3     
Name1    Gender1    Name2    Gender2    Group
A        M          B        F          A1
C        M          D        M          A2
E        F          F        F          A3

3 个答案:

答案 0 :(得分:1)

类似的东西:

select t1.name, t1.gender, t2.name, t2.gender, t1.group 
from student t1, student t2 
where t1.group = t2.group and t1.id < t2.id

答案 1 :(得分:0)

SELECT s1.name AS Name1, s1.gender AS Gender1, 
       s2.name AS Name2, s2.gender AS Gender2, 
       groups.group_s
FROM (
  SELECT MIN(id) AS st_first, MAX(id) AS st_second, group_s
  FROM students
  GROUP BY group_s
) AS groups
LEFT JOIN students s1 ON groups.st_first=s1.id
LEFT JOIN students s2 ON groups.st_second=s2.id

students是您的表的名称,group_s是组列

答案 2 :(得分:0)

这是完整的例子。

CREATE TABLE testing
(id char(10),
name char(10),
gender char(1),
grp char(10))

insert into testing values ('1','A','M','A1')
insert into testing values ('2','B','F','A1')
insert into testing values ('3','C','M','A2')
insert into testing values ('4','D','M','A2')
insert into testing values ('5','E','F','A3')
insert into testing values ('6','F','F','A3')


    select name1, gender1, name2, gender2, a.grp  from
    (
    SELECT name1 = CASE CONVERT(int,id)%2 WHEN 1 THEN name ELSE null END,
            gender1 = CASE CONVERT(int,id)%2 WHEN 1 THEN gender ELSE null END,
            grp FROM testing where CONVERT(int,id)%2 =1
    ) a 
    left join 
    (
    SELECT name2 = CASE CONVERT(int,id)%2 WHEN 0 THEN name ELSE null END,
            gender2 = CASE CONVERT(int,id)%2 WHEN 0 THEN gender ELSE null END,
            grp FROM testing where CONVERT(int,id)%2 =0
    ) b on a.grp=b.grp