2010-07-19 144 views
1

我有一個問題,我希望有人可以幫助。 我並不擅長SQL編程,所以我需要你們的幫助。SQL循環問題

這是我的問題,我有客戶代碼可能有2或3個地址。 樣本:

cust1 address1 
cust1 address2 
cust1 address3 
cust2 address1 
cust2 address2 

我想生成.NET的報告是這樣的:

cust1 address1 address2 address3 
cust2 address1 address2 

有人能幫忙嗎?

+0

聽起來像一個支點查詢,但它會是不錯的有數據樣本和基於該數據的預期輸出。你怎麼知道哪個地址是第一/第二/第三/等,以及這是什麼數據庫? – 2010-07-19 02:18:23

+0

如果您發佈代碼,XML或固定表格結構,請**在文本編輯器中突出顯示這些行,然後單擊編輯器工具欄上的「代碼」按鈕(101 010)以更好地格式化和語法突出顯示它!不需要麻煩 標記的東西..... – 2010-07-19 05:07:46

回答

1

這是假設2個表:

select 
    custName, A1.Address + ' ' + A2.Address + ' ' + A3.Address 
from 
    Customers as C 
    inner join Address as A1 on A1.CustKey = C.CustKey 
    inner join Address as A2 on A2.CustKey = C.CustKey and A1.AddressKey <> A2.Addresskey 
    left join Address as A3 on A3.CustKey = C.CustKey and A3.AddressKey <> A1.AddressKey and A3.AddressKey <> A2.AddressKey 

編輯顯示:

這假定1個表:

select 
    A1.Customer, 
    A1.Address + ' ' + A2.Address + ' ' + A3.Address 
from 
    Customer as A1 
    inner join Customer as A2 on A2.CustKey = A.CustKey and A1.Address <> A2.Address 
    left join Customer as A3 on A3.CustKey = A.CustKey and A3.Address <> A1.Address and A3.Address <> A2.Address 
+0

謝謝先生,我會嘗試這一個。 – pilots 2010-07-19 02:28:00