2010-08-20 116 views
0

我有一個查詢,我無法正常工作。我有3張桌子; Person,PersonProgram和Category。優先查詢

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

Person表對每個人有1條記錄,PersonProgram對每個人有多個程序。有四個類別,我需要拉入每個人的單行,並與每個類別的特定程序。

人表:

1 
2 
3 

PersonProgram表

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

期望的結果應該是什麼:

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

的問題是,有每個人的多個程序記錄和類別代碼爲1,2或3.我需要優先考慮代碼1,然後代碼3和忽略剩下的只剩下1條記錄,如果不存在則返回NULL。

我失去它試圖讓它工作。

僅供參考,它必須在視圖中。

感謝您的任何幫助。

回答

1
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 

返回

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

這是從你期望的結果不同。 (儘管我可以通過使用pp2.Category而不是pp2.ID來達到同樣效果)你能澄清一下嗎?

+1

在我的例子中的結果可能是錯誤的,方式長這個查詢。我會看看這個,看起來很有前途。週五放棄時間:) – 2010-08-20 22:59:09

+0

在視圖中可以使用'ROW_NUMBER'嗎?如果我添加SSMS每次崩潰。使用SQL 2005. – 2010-08-23 15:55:03

+0

@durilai - 是的。如果設計者無法應付它,試着通過腳本'CREATE VIEW dbo.ViewName AS WITH pp2 AS ...'來做到這一點'' – 2010-08-23 15:59:12