将两列联系在一起

时间:2014-10-15 04:02:15

标签: sql oracle

我有这个SQL语句:

select DISTINCT id_etudiant,g1.id_cours,note
from etudiant NATURAL JOIN inscription NATURAL JOIN groupe g1,groupe g2
where g1.id_cours = g2.id_cours
group by id_etudiant,g1.id_cours,note
having count(g1.id_cours) > 1
order by id_etudiant asc
;

这给出了这个结果:

ID_ETUDIANT   ID_COURS   NOTE
----------- ----------   ----
    1            8        E
    2            1        A
    2            2        A
    2            3        B
    3            1        B
    3            1        E
    3            2
    3            3        B
    8            8        E
    8            8

所以我的问题是,我如何获得这个结果?

ID_ETUDIANT   ID_COURS     NOTE
-----------   --------     ----
     3             1        B
     3             1        E
     8             8        E
     8             8

我不好问如何提出问题我很抱歉这个

3 个答案:

答案 0 :(得分:0)

从您的原始查询开始(我跳过了DISTINCT,因为它不是必需的)并且假设您只想要具有相同etudiant和cours但不同音符的行,此查询可能会帮助您:

SELECT id_etudiant, id_cours, note
  FROM(
     SELECT id_etudiant, g1.id_cours, note,
            COUNT(*) OVER (PARTITION BY id_etudiant, g1.id_cours) cnt
       FROM etudiant 
    NATURAL 
       JOIN inscription 
    NATURAL 
       JOIN groupe g1, groupe g2
      WHERE g1.id_cours = g2.id_cours
      GROUP 
         BY id_etudiant, g1.id_cours, note
     HAVING COUNT(g1.id_cours) > 1
      )
 WHERE cnt > 1     
 ORDER 
    BY id_etudiant ASC;

答案 1 :(得分:0)

因此,根据您在评论中的回复,我相信您希望etudiant具有相同cours的行不止一次。

我认为您遇到的查询问题是它包含注释。试试这个简化版本:

select DISTINCT id_etudiant,g1.id_cours
from etudiant NATURAL JOIN inscription NATURAL JOIN groupe g1,groupe g2
where g1.id_cours = g2.id_cours
group by id_etudiant,g1.id_cours
having count(g1.id_cours) > 1
order by id_etudiant asc
;

如果它给出正确的行,则在最后添加注释:

select table1.id_etudiant, table1.id_cours, table2.note 
from ( 
select DISTINCT id_etudiant,g1.id_cours
from etudiant NATURAL JOIN inscription NATURAL JOIN groupe g1,groupe g2
where g1.id_cours = g2.id_cours
group by id_etudiant,g1.id_cours
having count(g1.id_cours) > 1
) as table1, 
left outer join inscription as table2 
on table1.id_etudiant = table2.id_etudiant and table1.id_cours = table2.id_cours
order by id_etudiant, id_cours
;

如果有样本表结构和数据可供使用,这将更容易。

答案 2 :(得分:0)

像这样使用COUNT()OVER():

select
      ID_ETUDIANT, ID_COURS, NOTE
from (
      select
              ID_ETUDIANT, ID_COURS, NOTE
            , COUNT(*) OVER(PARTITION BY ID_ETUDIANT, ID_COURS) as x
      from existing_query
      ) 
where x > 1

将产生:

| ID_ETUDIANT | ID_COURS |   NOTE |
|-------------|----------|--------|
|           3 |        1 |      B |
|           3 |        1 |      E |
|           8 |        8 |      E |
|           8 |        8 | (null) |