2013-05-13 46 views
0

我看起来像这样的两个表:问题与多行合并成单排

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

请问您能提供一些示例数据行和预期输出吗? – gordatron 2013-05-13 15:59:45

+0

向我们提供您正在使用的查询的SQL,我们将帮助您改进它。另外,你使用的是什么数据库?一些对这类事情有用的分组选项是特定于数据库的。 – 2013-05-13 15:59:47

+0

以什么方式组合它们? – 2013-05-13 15:59:47

回答

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

+0

我的情况是不使用MAX()参数。这固定了一切!谢谢 :) – 2013-05-13 16:17:09