-2

i have two table 'ga_mise_en_stage' alias 'm'

and 'ga_annee_academique' alias 'ac', and

on 'ga_annee_academique' there is foreign key that point to 'ga_mise_en_stage'.

It is difficult for me to make query to retrive m.code_mise_stage, m.Libelle and all ac.annee_academique that related to m.code_mise_stage in the same ligne

schema for ga_mise_en_stage : code_mise_enstage(pk), libelle

schema for ga_annee_academique : code_annee_academique(pk), annee_academique, code_mise_en_stage(fk)

I want comma seperated result for m.*, "ac.annee_academique, ..."

Anish Shah
  • 7,669
  • 8
  • 29
  • 40
ucef
  • 557
  • 3
  • 10
  • 27

2 Answers2

1

You need to join on your foreign key..

select m.code_mise_stage, m.Libelle, ac.annee_academique, ac.*
FROM ga_annee_academique ac
inner join ga_mise_en_stage m
on ac.code_mise_en_stage = m.code_mise_enstage

EDIT: Comma seperated list - This works only on SQL Server

SELECT  m.code_mise_stage, m.Libelle, STUFF((SELECT  ',' + ac.annee_academique
            FROM ga_annee_academique ac
            WHERE  m.code_mise_enstage=ac.code_mise_en_stage
        FOR XML PATH('')), 1, 1, '') AS listStr
FROM ga_mise_en_stage m
GROUP BY m.code_mise_stage, m.Libelle

EDIT: Using system table to make this example more generic.

select t.TABLE_NAME, STUFF
(
    (select ', ' + c.COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS c 
        WHERE c.TABLE_NAME = t.TABLE_NAME FOR XML PATH(''))
    , 1,1, ''
)
from INFORMATION_SCHEMA.TABLES t where TABLE_NAME = 'ga_mise_en_stage'

Here is a documentation on XML PATH

In this example, query below returns XML as a string where each element is seperated by ',' which is used as an XML element.

select ', ' + c.COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS c 
        WHERE c.TABLE_NAME = 'FormulaMetrics_tbl' FOR XML PATH('')
Shantanu Gupta
  • 20,688
  • 54
  • 182
  • 286
0

the Query will be like that :

 select M.LIBELLE_STAGE, M.CODE_MISE_STAGE, JOINATE.anneeAcademique from ga_mise_en_stage m
 inner join (select AC.CODE_MISE_EN_STAGE, listagg(AC.ANNEE_ACADEMIQUE, ',') within group (order by AC.CODE_MISE_EN_STAGE) as anneeAcademique from ga_annee_academique ac
  group by AC.CODE_MISE_EN_STAGE) joinate 
  on JOINATE.CODE_MISE_EN_STAGE = M.CODE_MISE_STAGE
ucef
  • 557
  • 3
  • 10
  • 27