2014-12-31 33 views
0

我想從同一個表中的兩列中獲取不同的數據。從兩列獲取不同的數據SQL Server

表1:

***ID Address   City*** 
    01 Test Street  Springdale 
    01 Main Street  Springdale 
    01 Pass Dr.   New Town 
    01 Main Street  New Town 

我希望結果是這樣的;

***Address   City*** 
    Test Street  Springdale 
    Main Street  New Town 
    Pass Dr. 

目前我有這樣的:

SELECT DISTINCT Address 
    FROM Table1 
    WHERE ID = 01 
UNION 
SELECT DISTINCT City 
    FROM Table1 
    WHERE ID = 01 

但我得到的回報是:

***Address*** 
Test Street  
Main Street  
Pass Dr. 
Springdale 
New Town 
+2

您所需的輸出看起來很奇怪,原因有幾個。 1)爲什麼'Pass Dr.'對'City'列沒有價值? 2)你似乎在任意選擇一個城市來展示「大街」。這是真的? –

+0

您可能需要的是一個返回多個結果集的查詢,而不是試圖將這兩個地址和城市放在同一個結果集中。 – tvanfosson

+1

爲什麼你會*希望你的輸出看起來像這樣?這太殘酷了!你的起始表數據對我來說看起來很好。每個城市和地址對都應該是唯一的,但您應該考慮整行,而不是單獨列。 **編輯:*除非*您不再將列與相互關聯。 – mbomb007

回答

0

使用嵌套的CTE如下將產生在OP所需的結果集:

;WITH CTE_Address AS 
(
    SELECT DISTINCT Address 
    FROM #T 
), CTE_Address_rn AS 
(
    SELECT Address, ROW_NUMBER() OVER (ORDER BY Address) AS rn 
    FROM CTE_Address 
), CTE_City AS 
(
    SELECT DISTINCT City 
    FROM #T 
), CTE_City_rn AS 
(
    SELECT City, ROW_NUMBER() OVER (ORDER BY City) AS rn 
    FROM CTE_City 
) 
SELECT a.Address, c.City 
FROM CTE_Address_rn AS a 
LEFT JOIN CTE_City_rn AS c ON a.rn = c.rn 

的基本思想是,以產生含有不同的地址兩個單獨的結果集和城市和由ROW_NUMBER加入這些。

SQL Fiddle Demo here

P.S.上面的答案是基於這樣的假設,即OP只是希望將不同的地址和城市值放在一個表中,彼此分離。

+0

這樣做的確有用。謝謝。 – user3653252

0

這是因爲你永遠只選擇一列。工會只是把兩個數據集放在一起,並減少。所以第一個讀取不同的地址和第二個不同的城市,然後回退爲一個列表。

你應該真的返回這些作爲兩個不同的數據集或使用兩個不同的過程。你可以做前者只是擺脫你的聯盟。

0
;WITH CTE_Address AS 
(
    SELECT ID, Street_Address, DENSE_RANK() over (Order by Street_Address) as Denserank_Street 
    FROM The_Table 
), 
CTE_City AS 
(
    SELECT ID, City_Name, DENSE_RANK() over (Order by City_Name) as Denserank_City 
    FROM The_Table 
) 

SELECT a.Address, c.City 
FROM CTE_Address AS A 
INNER JOIN CTE_City AS C ON A.ID = C.ID 

P.S. Without the ID column, the JOIN statement will give wrong match between City and Address.