Question

J'ai une requête que je ne peux pas se rendre au travail à droite. J'ai 3 tables; Personne, PersonProgram et catégorie.

Person: ID, ....    
PersonProgram: ID, PersonID, Category, Code ...    
Category: ID, ...

La table personne a 1 dossier pour chaque personne et le PersonProgram a plusieurs programmes par personne. Il y a 4 catégories et je dois tirer dans une seule rangée, de chaque personne, avec le programme de spécifique de chaque catégorie.

Personne Tableau:

1
2
3

PersonProgram Tableau

1, 1, 1, 1
2, 1, 2, 1
3, 1, 1, 3
4, 2, 1, 1
5, 2, 3, 3

Qu'est-ce que le résultat souhaité doit être:

PersonID, ProgramIDforCat1, ProgramIDforCat2, ProgramIDforCat3, ProgramIDforCat4
1, 1, 2, NULL, NULL
2, 1, NULL, 3, NULL

Le problème est qu'il ya plusieurs enregistrements de programme pour chaque personne et catégorie avec un code de 1, 2 ou 3. Je dois mettre la priorité sur le code 1, alors le code 3 et ignorer le reste, tout en tirant seulement 1 disque, ou NULL si elle n'existe pas.

Je suis perdre en essayant d'obtenir ce travail.

Pour votre information, il doit être en vue.

Merci pour toute aide.

Était-ce utile?

La solution

WITH Person AS
(
SELECT 1 AS ID UNION ALL
SELECT 2 AS ID UNION ALL
SELECT 3 AS ID
),
PersonProgram AS
(
SELECT 1 AS ID, 1 AS PersonID, 1 AS Category, 1 AS Code UNION ALL
SELECT 2, 1, 2, 1 UNION ALL
SELECT 3, 1, 1, 3 UNION ALL
SELECT 4, 2, 1, 1 UNION ALL
SELECT 5, 2, 3, 3
),
pp2 AS
(
SELECT *
,ROW_NUMBER() OVER 
 (PARTITION BY PersonID, Category 
      ORDER BY CASE WHEN Code = 1 THEN 0 ELSE 1 END,
               CASE WHEN Code = 3 THEN 0 ELSE 1 END) AS RN
 FROM PersonProgram
)
select PersonID ,
max(case when Category =1 then pp2.ID end) ProgramIDforCat1,
max(case when Category =2 then pp2.ID end) ProgramIDforCat2,
max(case when Category =3 then pp2.ID end) ProgramIDforCat3,
max(case when Category =4 then pp2.ID end) ProgramIDforCat4
from Person p join pp2 
on pp2.PersonID = p.ID
WHERE RN=1
group by PersonID

retour

PersonID    ProgramIDforCat1 ProgramIDforCat2 ProgramIDforCat3 ProgramIDforCat4
----------- ---------------- ---------------- ---------------- ----------------
1           1                2                NULL             NULL
2           4                NULL             5                NULL

Ceci est différent de vos résultats attendus. (Bien que je peux faire la même chose en utilisant pp2.Category plutôt que pp2.ID) Pouvez-vous préciser?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top