优先查询

时间:2010-08-20 22:23:59

标签: sql-server-2005 sql-view

我有一个查询,我无法正常工作。我有3张桌子;人,人,程序和类别。

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

Person表每个人有1条记录,PersonProgram每人有多个程序。有4个类别,我需要将每个人划分为一行,每个类别都有特定的程序。

人员表:

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 个答案:

答案 0 :(得分: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使其相同)你能澄清一下吗?