Bạn có thể sử dụng CTE để thu thập dữ liệu trong khi xoay các số điện thoại thành danh sách được phân tách bằng dấu phẩy. Nó có thể không hiệu quả, nhưng nó là một thủ thuật tiện dụng.
Sau đây chạy trên AdventureWorks2008R2, mặc dù bạn sẽ cần thêm một số dữ liệu vào bảng Person.PersonPhone để tạo nhiều số điện thoại cho một kiểu người/số.
; with PersonsWithTelephoneNumbersCTE (
BusinessEntityId, FirstName, MiddleName, LastName,
PhoneNumberTypeId, PhoneNumber, PhoneNumbers, Elements)
as (
-- Base case: Just the person identifications with all possible phone types.
select BusinessEntityID, FirstName, MiddleName, LastName, PhoneNumberTypeId,
cast('' as NVarChar(25)), cast('' as VarChar(MAX)), 0
from Person.Person as PP cross join
Person.PhoneNumberType as PNT
union all
-- Add a telephone number.
select CTE.BusinessEntityId, CTE.FirstName, CTE.MiddleName, CTE.LastName,
PNT.PhoneNumberTypeID, PN.PhoneNumber,
cast(CTE.PhoneNumbers + ', ' + PN.PhoneNumber as VarChar(MAX)), CTE.Elements + 1
from PersonsWithTelephoneNumbersCTE as CTE inner join
Person.Person as PP on PP.BusinessEntityID = CTE.BusinessEntityId inner join
Person.PhoneNumberType as PNT on PNT.PhoneNumberTypeID = CTE.PhoneNumberTypeId inner join
Person.PersonPhone as PN on PN.BusinessEntityID = CTE.BusinessEntityId and PN.PhoneNumberTypeID = PNT.PhoneNumberTypeID
where PN.PhoneNumber > CTE.PhoneNumber
)
-- Get the person and the longest list of phone numbers for each person/phone type.
select LastName, FirstName, MiddleName,
(select Name from Person.PhoneNumberType where PhoneNumberTypeID = Edna.PhoneNumberTypeID) as PhoneNumberType,
substring(PhoneNumbers, 3, len(PhoneNumbers) - 2) as PhoneNumbers from (
select BusinessEntityID, FirstName, MiddleName, LastName, PhoneNumberTypeId, PhoneNumbers,
rank() over (partition by BusinessEntityId, PhoneNumberTypeId order by Elements desc) as Ranking
from PersonsWithTelephoneNumbersCTE
) as Edna
where Ranking = 1 and PhoneNumbers <> ''
order by LastName, FirstName, MiddleName, PhoneNumberType
Tôi không hiểu những gì bạn đang yêu cầu. Bạn có thể rephrase nó? –
Tắt chủ đề: Những gì bạn đang yêu cầu là có thể. Thứ nhất, điều này đang được tiêu thụ bởi một ứng dụng .NET? Tôi hỏi bởi vì nó sẽ sạch hơn nhiều để thực hiện chuyển đổi trong LINQ –
@Neil Fenwick Đúng vậy. Xin vui lòng giải thích làm thế nào để tôi làm điều này bằng cách sử dụng LINQ? – Shahin