2016-02-25 76 views
1

我是新來的,所以如果這種類型的問題已經被問到,請耐心等待,我會嘗試儘可能清楚。就這樣說,我正試圖將下面的數據錶轉換爲所需的格式。所有想法都有幫助。在SQL Server中轉換數據

PhType  PhNumber  Sequence 
------------------------------------- 
Cell Phone 111-222-3333  2 
Cell Phone 222-333-4444  5 
Home Phone 999-222-1111  6 
Home Phone 555-444-3333  8 

我試圖將數據轉換成此表。

**CellPhone1#** **Sequence** **CellPhone2#** **Sequence** **HomePhone1#** **Sequence** **HomePhone2#** **Sequence**                    
111-222-3333 ---- 2 ------  222-333-4444 -----  5 ---------  999-222-1111 ----- 6  -------  555-444-3333 ----------  8 

的想法正在轉向數據的行轉換成列,但由於對數字的序列不按順序我有一個困難時期沒有在我的數據差距這樣做。目前,我將信息轉換成列在加入級

LEFT OUTER JOIN 
    Reports.dbo.BorrowerTelephones BT with(nolock) ON B1.HHNbr = BT.HHNbr 
                AND B1.NamSeq = BT.NamSeq 
                AND BT.Seq = 0 
                AND BT.PhType = 'Cell Phone' 
LEFT OUTER JOIN 
    Reports.dbo.BorrowerTelephones BT1 with(nolock) ON B1.HHNbr = BT1.HHNbr 
                AND B1.NamSeq = BT1.NamSeq 
                AND BT1.Seq = 1 
                AND BT1.PhType = 'Cell Phone' 

但是如果沒有在手機phtype會留下那些列空的序列0或1的電話號碼。我需要查詢將序列從等式中排除,而不必在下一列中重複電話號碼。請幫忙。

感謝, 米奇

回答

0

所以,據我所知,你只是想在你的桌子下崩潰的數據單行,是否正確?我寫了一個SQL查詢,它使用ROW_NUMBER()來測試我認爲你想要處理序列號中的差距。我希望這能讓你瞭解你需要什麼。

CREATE TABLE #testPhones (
    PhType VARCHAR(20), 
    PhNumber VARCHAR(12), 
    PhSequence INT) 

INSERT INTO #testPhones(PhType, PhNumber, PhSequence) 
VALUES('Cell Phone', '111-222-3333', 3), 
     ('Cell Phone', '222-333-4444', 5), 
     ('Home Phone', '999-222-1111', 6), 
     ('Home Phone', '555-444-3333', 8) 

SELECT ROW_NUMBER() OVER(ORDER BY PhSequence) AS Row, * 
FROM #testPhones 

SELECT A.PhNumber AS CellPhone1#, A.PhSequence AS PhSequence, 
    B.PhNumber AS CellPhone2#, B.PhSequence AS PhSequence, 
    C.PhNumber AS HomePhone1#, C.PhSequence AS PhSequence, 
    D.PhNumber AS HomePhone2#, D.PhSequence AS PhSequence 
FROM (SELECT PhNumber, PhSequence FROM (SELECT ROW_NUMBER() OVER(ORDER BY PhSequence) AS RowNo, * FROM #testPhones) AS A WHERE RowNo = 1) AS A 
    LEFT OUTER JOIN (SELECT PhNumber, PhSequence FROM (SELECT ROW_NUMBER() OVER(ORDER BY PhSequence) AS RowNo, * FROM #testPhones) AS B WHERE RowNo = 2) AS B ON 1=1 
    LEFT OUTER JOIN (SELECT PhNumber, PhSequence FROM (SELECT ROW_NUMBER() OVER(ORDER BY PhSequence) AS RowNo, * FROM #testPhones) AS C WHERE RowNo = 3) AS C ON 1=1 
    LEFT OUTER JOIN (SELECT PhNumber, PhSequence FROM (SELECT ROW_NUMBER() OVER(ORDER BY PhSequence) AS RowNo, * FROM #testPhones) AS D WHERE RowNo = 4) AS D ON 1=1 

DROP TABLE #testPhones 

此輸出以下兩個表:

Output Tables

+0

謝謝托馬斯,ROW_NUMBER函數的工作完美。再次感謝你的幫助! – Mitchel

+0

非常歡迎。 –