我有一点sql,几乎做我想要做的事情.我正在使用三个表,一个Users,UserPhoneNumbers和UserPhoneNumberTypes.我正在尝试通过电话号码获取用户列表以进行导出.
数据库本身是旧的,有一些完整性问题.我的问题是数据库中每个电话号码应该只有1种,但情况并非如此.当我运行它时,如果每个人包含两个“Home”数字,则可以得到多行结果.
如何修改sql以获取列出的第一个电话号码,并忽略其余的号码?我在sql Server中,我知道TOP语句.但是,如果我将“TOP 1”添加到LEFT JOIN select语句中,那么它只会给出数据库中的第一个条目,而不是每个用户的第一个条目.
这是针对sql Server 2000.
谢谢,
SELECT Users.UserID,Users.FirstName,Users.LastName,HomePhone,WorkPhone,FaxNumber FROM Users LEFT JOIN (SELECT UserID,PhoneNumber AS HomePhone FROM UserPhoneNumbers LEFT JOIN UserPhoneNumberTypes ON UserPhoneNumbers.UserPhoneNumberTypeID=UserPhoneNumberTypes.UserPhoneNumberTypeID WHERE UserPhoneNumberTypes.PhoneNumberType='Home') AS tmpHomePhone ON tmpHomePhone.UserID = Users.UserID LEFT JOIN (SELECT UserID,PhoneNumber AS WorkPhone FROM UserPhoneNumbers LEFT JOIN UserPhoneNumberTypes ON UserPhoneNumbers.UserPhoneNumberTypeID=UserPhoneNumberTypes.UserPhoneNumberTypeID WHERE UserPhoneNumberTypes.PhoneNumberType='Work') AS tmpWorkPhone ON tmpWorkPhone.UserID = Users.UserID LEFT JOIN (SELECT UserID,PhoneNumber AS FaxNumber FROM UserPhoneNumbers LEFT JOIN UserPhoneNumberTypes ON UserPhoneNumbers.UserPhoneNumberTypeID=UserPhoneNumberTypes.UserPhoneNumberTypeID WHERE UserPhoneNumberTypes.PhoneNumberType='Fax') AS tmpFaxNumber ON tmpFaxNumber.UserID = Users.UserID