繁体   English   中英

将多行组合成单行的问题

[英]Issue with multiple rows combining into single row

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

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

您可以将聚合函数与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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM