我有一個很大的(ish)數據庫。簡單地把客戶記錄。現在我有兩張桌子;一個是CustomerInfo
和PhoneNumbers
。一些樣本數據是,在SQL Server中爲每條記錄創建行到列
CustomerInfo
`````````````
CustID | CustName | CustomerLocation
--------+---------------+--------------------
1 | Paul | Bristol
2 | Eugin | Bournemouth
3 | Francis | London
PhoneNumbers
````````````
PhoneID | CustID | PhoneNumber
--------+-----------+----------------
1 | 1 | 0117123456
2 | 2 | 0120212345
3 | 2 | 0784256864
4 | 3 | 0204587895
現在,你可以看到,Paul
和Francis
只有一個號碼,但Eugin
有兩個。在一個正常的世界,如果我加入了兩個表,
SELECT
c.CustName,
p.PhoneNumber
FROM
CustomerInfo c
JOIN
PhoneNumbers p
ON c.CustID = p.CustID
我會得到,
CustName | PhoneNumber
------------+--------------------
Paul | 0117123456
Eugin | 0120212345
Eugin | 0784256864
Francis | 0204587895
這是對的,但我運行另一個查詢需要的結果是,
CustName | PhoneNumber1 | PhoneNumber2
------------+-------------------+---------------
Paul | 0117123456 | NULL
Eugin | 0120212345 | 0784256864
Francis | 0204587895 | NULL
我可以寫一個函數的表變量。但由於這將成爲查詢的一部分,我希望是否有其他解決方案。
編輯 -我想強調的部分,as this is going to be part of a Query, I was hoping if there were any other solution
,實際的查詢將是,
SELECT
per.[PersonId],
per.[ClientReference],
sal.SalutationName,
per.[FirstName],
per.[LastName],
per.[DateOfBirth],
per.[Password]
FROM
[Customers].[people].[Person] per
JOIN
[Customers].[people].[Salutation] sal
ON sal.SalutationId = per.SalutationId
我想是,
SELECT
per.[PersonId],
per.[ClientReference],
sal.SalutationName,
per.[FirstName],
per.[LastName],
per.[DateOfBirth],
per.[Password],
pn.[PhoneNumber1], --Made up column, there is only one column in the pn table
pn.[PhoneNumber2] --Made up column, there is only one column in the pn table
FROM
[Customers].[people].[Person] per
JOIN
[Customers].[people].[Salutation] sal
ON sal.SalutationId = per.SalutationId
JOIN
[Customers].[comms].[PhoneNumber] pn
ON per.PersonId = pn.PersonId
這是一個數據透視查詢。 **重要問題:**您是否可以爲每位客戶提供「無限制」的電話號碼?還是有限制? –
@SQLPolice,我目前沒有超過2個,但是。即使我們有,我也只想要前兩個。謝謝,我會研究這個。 :) – PaulFrancis