我在SQL Server 2014 Express上有这个SELECT:
SELECT DISTINCT Name, Lastname, Phone1, Phone2, Phone3, ... PhoneN
FROM TableX
WHERE Phone1 <> ''
现在结果如下:
Name Lastname Phone1 Phone2 Phone3 ...
James Brown 68798768
James Brown 98761456
Alice Grey 66687974
Peter Thompson 87997555
Peter Thompson 87997444
Peter Thompson 87997333
我需要一个SELECT,让我们回复一下那些同名的人的电话:
Name Lastname Phone1 Phone2 Phone3 ...
James Brown 68798768 98761456
Alice Grey 66687974
Peter Thompson 87997555 87997444 87997333
有任何疑问吗?
谢谢!
答案 0 :(得分:3)
如果您拥有最大数量的手机并且不需要动态,那么条件聚合可能会有所帮助
Select Name
,LastName
,Phone1 = max(case when RN=1 then Phone1 else '' end)
,Phone2 = max(case when RN=2 then Phone1 else '' end)
,Phone3 = max(case when RN=3 then Phone1 else '' end)
,Phone4 = max(case when RN=4 then Phone1 else '' end)
From (
Select *
,RN = Row_Number() over (Partition By Name,LastName Order By Phone1)
From YourTable
) A
Group By Name,LastName
答案 1 :(得分:0)
考虑到您最多只有10个电话号码,您可以执行类似....
Select *
FROM (
Select *
,'Phone-' + CAST(ROW_NUMBER() OVER (PARTITION BY Name, LastName
ORDER BY Phone1) AS VARCHAR(10)) PhoneNum
FROM TableName
) t
PIVOT (MAX(Phone1)
FOR PhoneNum
IN ([Phone-1],[Phone-2],[Phone-3],[Phone-4],[Phone-5],
[Phone-6],[Phone-7],[Phone-8],[Phone-9],[Phone-10])
)p