2015-11-24 34 views
-2

我的表合併類似於:SQL Server的支點

Seller_ID |From  |To   |Depart_Date   |Arrival_Date 
------------------------------------------------------------------------------------- 
Paul  |office  |client_23  |10/20/2015 3:30:00 PM |10/21/2015 7:54:00 AM 
Paul  |client_23 |client_ 88fe |10/21/2015 11:55:00 AM |10/22/2015 8:11:00 PM 
Paul  |client_88fe |client_avr4 |10/23/2015 3:57:00 PM |10/26/2015 11:27:00 AM 
Paul  |client_avr4 |home   |10/26/2015 5:28:00 PM |10/28/2015 3:39:00 PM 

我沒有像第一次,第二次,第三次訪問一個指標...
第一次訪問總是有'從'=辦公室和上次訪問總是有'到'=家。
才使該序列的方式或者是倒退的日期(或從-到??)

我期望的結果將是:

|Seller_ID |from  |office_departure  |client1  |clt1_arrival   |clt1_departure   |client2  |clt2_arrival   |clt2_departure   |client3 |clt3_arrival    |clt3_departure   |home_arrival 
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
|Paul  |office |10/20/2015 3:30:00PM |client_23 |10/21/2015 7:54:00 AM|10/21/2015 11:55:00 AM |client_ 88fe|10/22/2015 8:11:00 PM |10/23/2015 3:57:00 PM |client_avr4 |10/26/2015 11:27:00 AM |10/26/2015 5:28:00 PM |10/26/2015 5:28:00 PM 

任何幫助apreciated! 在此先感謝。

+0

你有什麼嘗試?你的Pivot/Unpivot沒有成功嗎?或者你會不明白這個語法? –

回答

0

如果你的情況是每個賣家只是一次旅行,或者你有其他領域的這裏沒有顯示,您可以通過在組使用,你可以使用這樣的事情:

select 
    Seller_ID, 
    max(case when RN = 1 then [From] end), 
    max(case when RN = 1 then [Depart_Date] end), 
    max(case when RN = 1 then [Arrival_Date] end), 
    max(case when RN = 2 then [From] end), 
    max(case when RN = 2 then [Depart_Date] end), 
    max(case when RN = 2 then [Arrival_Date] end) 
from (
    select 
    row_number() over (partition by Seller_ID 
         order by Depart_Date asc) as RN, 
    * 
    from Table1 
) X 
group by Seller_ID 

結果:

Seller_ID      
Paul office October, 20 2015 15:30:00 October, 21 2015 07:54:00 client_23 October, 21 2015 11:55:00 October, 22 2015 20:11:00 

實例SQL Fiddle

如果你沒有任何現場跟蹤行程的數量,你可以使用運行總計在出發日期聲明的順序case when [From] = 'office' then 1 else 0 end由Seller_ID分區,然後爲行分配行程編號。

+0

抱歉的傢伙只是太多的小時看代碼,我只是沒有看到它!感謝JamesZ完美的作品 – ruisadias