从两列SQL Server获取不同的数据

时间:2014-12-31 21:53:36

标签: 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

3 个答案:

答案 0 :(得分:0)

这是因为你只选择了一列。联盟只是将两个数据集放在一起并进行deupes。所以第一个读取不同的地址和第二个不同的城市,然后作为一个列表返回。

您应该将这些作为两个不同的数据集返回或使用两个不同的过程。你可以做前者只是摆脱你的UNION。

答案 1 :(得分: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只是希望将不同的地址和城市值放在一个表中,彼此不相关。

答案 2 :(得分: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.