2012-08-13 122 views
3

假设我有id, name, phone_type, phone_no如何将两条记录合并成一条线?

和一张桌子我有2个记录

{1, Tom, home, 123} 
{2, Tom, mobile, 234} 

如果我只是用SQL:

SELECT * FROM table WHERE name = tom; 

它会显示两条记录。

不过,我想在这样一个线显示:

Tom, mobile,234,home,123 

类似的东西...

我怎么能修改在DB2中的SQL?

请帮忙。

+0

你在输出中寻找什么列? – 2012-08-13 14:52:38

+0

**什么**数据库系统,以及哪个版本? * SQL *只是*结构化查询语言* - 许多数据库系统使用的语言,但不是数据库产品......这样的功能通常是特定于供应商的 - 因此我们确实需要知道**数据库系统**你正在使用.... – 2012-08-13 14:54:30

+0

看看http://stackoverflow.com/questions/194852/concatenate-many-rows-into-a-single-text-string中的答案 – 2012-08-13 14:55:20

回答

0

这里有一种方法:

select name, 
     'mobile', 
     max(case when ttype = 'mobile' then phone end) as mobilephone, 
     'home', 
     max(case when ttype = 'home' then phone end) as homephone 
from t 
group by name 
0

这可能会给一个想法

declare @rVal nvarchar(128) 
set @rVal = 'Tom' 
select @rVal = @rval + coalesce(',' + phoneType + ',' + convert(nvarchar,phoneNumber),'') from testTable where name = 'Tom' 
select @rVal 
+0

这是我的DB2版本(在iSeries上)无效的语法,并且不会返回反正连接的行(仅列,这很愚蠢)。而'COALESCE()'是没用的,因为它总是有数据(因为'','')。如果你期望这是在一个循环中运行......你需要在处理SQL时停止像命令程序员那样的思考(你正在与系统打交道)。 – 2012-08-14 16:17:07

1

下面是使用OLAP功能更通用的例子。这将获得每个名称的前四对电话类型和电话号码。如果有人少于四人,剩下的人将被填入NULL。很明显,你如何将这个扩展到四个以上。

select * from (
    select id, 
      min(id) over (partition by name) as first_id, 
      name, 
      phone_type as phone_type1, 
      phone_no as phone_no1, 
      lead(phone_type,1) over (partition by name order by id) as phone_type2, 
      lead(phone_no,1) over (partition by name order by id) as phone_type2, 
      lead(phone_type,2) over (partition by name order by id) as phone_type3, 
      lead(phone_no,2) over (partition by name order by id) as phone_type3, 
      lead(phone_type,3) over (partition by name order by id) as phone_type4, 
      lead(phone_no,3) over (partition by name order by id) as phone_type4 
    from table 
) where id = first_id 

外部选择保证你每人只能得到一行。您需要这样做是因为OLAP函数的结果(本例中为min(id))不能直接放入where子句中。

+0

并非所有版本的DB2都支持'lead()',尽管OP没有列出他正在使用的版本。这也将结果限制为4个电话号码 - 如果所有的OP需求都是2,我可能只是尝试自联接,而不是尝试使用OLAP功能;如果他需要超过4个,你将需要其他东西...... – 2012-08-14 16:22:58

+0

正如我所提到的,这将很容易扩展到4以上。只需添加更多的lead()线对,直到您可以处理最大值可能与您的数据的情况。不,这种解决方案并不美观,但遗憾的是,在DB2中没有一种好的方法来实现这一点。 – dan1111 2012-08-16 08:13:30