我想拍两张这样的唱片:
Id Fname Lname Email
------------------------------------
1 John Doe jdoe@example.com
2 John Doe doej1@place.net
并以这样的方式组合它们,我只有一条记录:
Id Fname Lname Email1 Email2
---------------------------------------------------
1 John Doe jdoe@example.com doej@place.net
如您所见,这将在我的记录中添加一个字段,否则数据库中不存在该字段.这是可能的还是我必须找到另一种方式?
注意:我无法以任何方式更改数据库结构.
最佳答案 数据库产品和版本在这里完全不同.假设您正在使用支持排名功能的东西(例如SQL Server 2005)
Select FName, LName
, Min( Case When Rnk = 1 Then Z.Email End ) As Email1
, Min( Case When Rnk = 2 Then Z.Email End ) As Email2
From (
Select FName, LName, Email
, Row_Number() Over ( Partition By FName, LName Order By Id ) As Rnk
From MyTable
) As Z
Group By Z.FName, Z.LName
如果您没有使用支持排名功能的产品(例如MySQL),那么它就更棘手了.一个应该适用于几乎所有数据库系统的解决方案是:
Select FName, LName
, Min( Case When Rnk = 1 Then Z.Email End ) As Email1
, Min( Case When Rnk = 2 Then Z.Email End ) As Email2
From (
Select FName, LName, Email
, (Select Count(*)
From MyTable As T2
Where T1.FName = T2.FName
And T2.LName = T2.LName
And T2.Id < T1.Id) + 1 As Rnk
From MyTable As T1
) As Z
Group By Z.FName, Z.LName