sql查询加入和连接值

时间:2015-06-20 21:40:09

标签: sql sql-server sql-server-2008 tsql sql-server-2005

sql server:2012

这是3张桌子。

第一个表是用户(顾问)表 第二个是价格表,第一列的每个用户都有一个价格 最后一张表定义了顾问提供服务的区域(城市)

Consultants      Prices           Area
uid | Name       uid | Price      uid | City
----|-----      -----|-------     ----|------
1   | Dave        1  |  5           1 | NY
2   | Adrian      2  |  7           1 | LA
3   | John        4  |  5           4 | NY
4   | Lee                           4 | NO
                                    4 | LA 
                                    4 | SF

我需要从所有表格中选择这样的内容:

uid  |  Price   | City
-----|----------|-------
 1   |    5     | NY, LA
-----|----------|-------
 2   |    7     | 
-----|----------|-------
 4   |    5     | NY, NO, LA, SF
-----|----------|-------

我该如何选择?有什么想法吗?

2 个答案:

答案 0 :(得分:1)

由于未指定数据库,假设SQL Server 2008,您可以使用STUFF functionGroup BY Clause将多行合并为单个逗号分隔值

Select C.uid, P.price, ISNULL(A.City,'') City
From Consultants C
     INNER JOIN Prices P ON C.uid = P.uid
     LEFT JOIN (
                 SELECT  UID
                         ,STUFF((SELECT ', ' + CAST(city AS VARCHAR(10)) [text()]
                         FROM Area
                         WHERE UID = t.UID
                         FOR XML PATH(''), TYPE)
                         .value('.','NVARCHAR(MAX)'),1,2,' ') CITY
                  FROM Area t
                  GROUP BY UID ) A 
      ON C.uid = A.uid

Working SQL Fiddle

答案 1 :(得分:1)

也许你可以这样做

declare @consultants table (uid int,name varchar(10))
insert into @consultants (uid,name)values (1,'dave'),(2,'adrian'),(3,'jon'),(4,'lee')
declare @Prices table (uid int,price int)
insert into @Prices(uid,price)values (1,5),(2,7),(4,5)

declare @Area table (uid int,city varchar(5))
insert into @Area(uid,city)values (1,'NY'),(1,'LA'),(4,'NY'),(4,'LA'),(4,'SF'),(4,'NO')

select t.uid,tt.price,ISNULL(STUFF((select  +', '+ city from @Area where uid = t.uid FOR XML PATH(''), TYPE)
                         .value('.','NVARCHAR(MAX)'),1,2,' '),'')CITY  from @consultants t INNER JOIN @Prices tt
ON t.uid = tt.uid