将多行组合成单行的问题

时间:2013-05-13 15:57:27

标签: sql

我有两个看起来像这样的表:

Table_X
id, cert_number, other random info

Table_Y
id, cert_number, type, name

问题出现是因为我在表y中有不同的类型,它们都适用于我想要返回的单个结果(即:所有者名称,运营商名称,目的地名称),这些结果基于该类型。

有没有办法可以将这些结果与owner_name,carrier_name和destination_name合并为一个结果?

我使用CASE正确地将信息输入到结果中,但是因为我在select语句中使用了type字段,所以我得到了每个cert_number的3个结果。

提前致谢!

编辑:

以下是一些示例数据。实际的SQL语句非常长,因为需要传递大量参数并检查。

table_x
 id  |  cert_number
 1       123-XYZ
 2       124-zyx

table_y
 id  |  cert_number |     type      |  name  
 1       123-XYZ      owner            bob
 2       123-XYZ      destination      paul
 3       124-zyx      owner            steve
 4       123-xyz      carrier          george
 5       124-zyx      carrier          mike
 6       124-zyx      destination      dan

1 个答案:

答案 0 :(得分:2)

您可以使用带有CASE表达式的聚合函数:

select x.cert_number,
  max(case when y.[type] = 'owner' then y.name end) owner_name,
  max(case when y.[type] = 'carrier' then y.name end) carrier_name,
  max(case when y.[type] = 'destination' then y.name end) destination_name
from table_x x
inner join table_y y
  on x.cert_number = y.cert_number
group by x.cert_number;

请参阅SQL Fiddle with Demo

或者您可以多次type加入您的桌子:

select x.cert_number,
  y1.name as owner_name,
  y2.name as carrier_name,
  y3.name as destination_name
from table_x x
left join table_y y1
  on x.cert_number = y1.cert_number
  and y1.type = 'owner'
left join table_y y2
  on x.cert_number = y2.cert_number
  and y2.type = 'carrier'
left join table_y y3
  on x.cert_number = y3.cert_number
  and y3.type = 'destination';

请参阅SQL Fiddle with Demo