选择相同的客户名称,但具有不同的客户地址

时间:2009-06-13 23:22:59

标签: sql-server tsql

尝试选择同一客户的所有记录,但地址不同的记录。

所以我稍后可以让用户选择Bob Yonkers,然后选择将Bob的所有记录更新为特定地址。所以我想展示所有可用的记录。

数据示例:

CUSTOMER_NAME, CUSTOMER_ADDRESS
Bob Yonkers  , 42 Satellite Cir
Bob Yonkers  , 667 Orbit St
Bob Yonkers  , 42 Satellite Cir
Bob Yonkers  , 667 Orbit St
David Boom   , 5959 Bush Ave
David Boom   , 5959 Bush Ave
David Boom   , 5959 Bush Ave
David Boom   , 5959 Bush Ave
David Boom   , 5959 Bush Ave
Ruby Tuesday , 123 Highway Ln Apt#1
Ruby Tuesday , 123 Highway Ln
David Boom   ,5959 Bush Ave
David Boom   ,5959 Bush Ave
David Boom   ,5959 Bush Ave

因此查询会带回这些结果......

结果示例:

CUSTOMER_NAME, CUSTOMER_ADDRESS
Bob Yonkers  , 42 Satellite Cir
Bob Yonkers  , 667 Orbit St
Ruby Tuesday , 123 Highway Ln Apt#1
Ruby Tuesday , 123 Highway Ln

任何帮助都将不胜感激。

4 个答案:

答案 0 :(得分:5)

SELECT * 
FROM [table] t1
INNER JOIN [table] t2 ON t1.Name=t2.Name AND t1.Address<>t2.Address

答案 1 :(得分:2)

这是乔尔的改进:

SELECT distinct t1.* 
FROM [table] t1
INNER JOIN [table] t2 ON t1.Name=t2.Name AND t1.Address<>t2.Address

答案 2 :(得分:0)

尝试一下......

select * from (select count(customername) as ct, customername, address from table group by customername, address) t1
where t1.ct>1

答案 3 :(得分:0)

这引起了我的兴趣,因为一位朋友问我类似的东西。下面的查询将解决问题,尽管效率不高:

mysql> select DISTINCT CUSTOMER_NAME,CUSTOMER_ADDRESS from CUST_ADDR where CUSTOMER_NAME in (select CUSTOMER_NAME from CUST_ADDR GROUP BY CUSTOMER_NAME HAVING COUNT(DISTINCT CUSTOMER_ADDRESS) > 1 );

+---------------+----------------------+
| CUSTOMER_NAME | CUSTOMER_ADDRESS     |
+---------------+----------------------+
| Bob Yonkers   | 42 Satellite Cir     |
| Bob Yonkers   | 667 Orbit St         |
| Ruby Tuesday  | 123 Highway Ln Apt#1 |
| Ruby Tuesday  | 123 Highway Ln       |
+---------------+----------------------+
4 rows in set (0.01 sec)

+---------------+----------------------+ | CUSTOMER_NAME | CUSTOMER_ADDRESS | +---------------+----------------------+ | Bob Yonkers | 42 Satellite Cir | | Bob Yonkers | 667 Orbit St | | Ruby Tuesday | 123 Highway Ln Apt#1 | | Ruby Tuesday | 123 Highway Ln | +---------------+----------------------+ 4 rows in set (0.01 sec)