我在想这可能是连接的问题?我试过Group by无济于事...... 任何建议都会被贬低!我已将查询放在下面:
*抱歉缺少详细信息 - Med_Prof_Record_No是唯一的值,我知道代码很乱 - 但这就是我到这里时的内容;-)这也是一个sql 2000的框,所以新的语法赢了工作......我已经清理了连接abit但是不想偏离原始查询太远 -
SELECT DISTINCT
P.Last_name + ', ' + P.First_name AS Full_name,
P.Degree,
F.Med_Prof_Record_No,
F.Current_status,
F.Status_category,
F.Department_name,
F.Section,
F.SPHAffiliatedPhysiciansSurgeons AS Affiliated,
S.Board_Name,
S.Specialty_Name,
O.Office_name,
O.Address_1,
O.Address_2,
O.City,
O.State,
O.Zip_Code,
O.Phone_number_1,
O.Fax_number
FROM
Med_Prof P, Med_Prof_Facilities F, Med_Prof_Specialties S, Med_Prof_Offices O
WHERE
(F.Med_Prof_Record_No = P.Med_Prof_Record_No) AND
(F.Med_Prof_Record_No = S.Med_Prof_Record_No) AND
(F.Med_Prof_Record_No = O.Med_Prof_Record_No) AND
<cfif URL.LastName is NOT "">(P.Last_name LIKE '#URL.LastName#%') AND</cfif>
<cfif URL.Specialty is NOT "">(F.Section = '#URL.Specialty#') AND</cfif>
<cfif URL.Group is NOT "">(O.Office_name LIKE '#URL.Group#%') AND</cfif>
(F.Status_category = 'active')
ORDER by Full_name
答案 0 :(得分:2)
这是一个刺。这假设你想要决定要显示哪个办公室等(在这种情况下它是任意的),P.Med_Prof_Record_No
是唯一的,只代表一个人(起初我认为Last_name
+ First_name
是唯一的,但这似乎是一个非常危险的假设),而且您使用的是SQL Server 2005或更高版本。最后,please use properly qualified object names和please, please, please stop using lazy implicit joins of the FROM foo, bar, blat, splunge
variety。
;WITH x AS
(
SELECT
P.Last_name + ', ' + P.First_name AS Full_name,
P.Degree,
F.Med_Prof_Record_No,
-- other columns from F,
S.Board_Name,
S.Specialty_Name,
O.Office_name,
-- other columns from O,
rn = ROW_NUMBER() OVER (PARTITION BY P.Med_Prof_Record_No
ORDER BY F.Current_status, S.Board_name, O.Office_name)
FROM
dbo.Med_Prof AS P
INNER JOIN
dbo.Med_Prof_Facilities AS F
ON P.Med_Prof_Record_No = F.Med_Prof_Record_No
INNER JOIN
dbo.Med_Prof_Specialties AS S
ON F.Med_Prof_Record_No = S.Med_Prof_Record_No
INNER JOIN
dbo.Med_Prof_Offices AS O
ON F.Med_Prof_Record_No = O.Med_Prof_Record_No
WHERE
<cfif ... AND</cfif>
-- other <cfif> clauses
(F.Status_category = 'active')
)
SELECT * FROM x WHERE rn = 1
ORDER BY Full_name;