Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 多行合并为单行的问题_Sql - Fatal编程技术网

Sql 多行合并为单行的问题

Sql 多行合并为单行的问题,sql,Sql,我有两张像这样的桌子: Table_X id, cert_number, other random info Table_Y id, cert_number, type, name 出现这个问题是因为表y中有不同的类型,它们都适用于我想要返回的基于类型的单个结果(即:所有者名称、承运人名称、目的地名称) 有没有一种方法可以将这些结果与所有者名称、承运人名称和目的地名称合并为一个结果 我使用CASE将信息正确地输入到结果中,但由于我在select语句中使用了type字段,因此每个证书号返回3个

我有两张像这样的桌子:

Table_X
id, cert_number, other random info

Table_Y
id, cert_number, type, name
出现这个问题是因为表y中有不同的类型,它们都适用于我想要返回的基于类型的单个结果(即:所有者名称、承运人名称、目的地名称)

有没有一种方法可以将这些结果与所有者名称、承运人名称和目的地名称合并为一个结果

我使用CASE将信息正确地输入到结果中,但由于我在select语句中使用了type字段,因此每个证书号返回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

您可以将聚合函数与
大小写
表达式一起使用:

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;

或者,您可以使用
类型在表中多次加入:

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,我们将帮助您改进。另外,您使用的是什么数据库?对这类事情有用的一些分组选项是特定于数据库的。以何种方式组合它们?能否显示一个查询示例?能否发布一些示例数据和所需结果?另外,请发布您正在使用的数据库产品以及您在此时尝试的查询。我的案例没有使用MAX()参数。这一切都解决了!谢谢:)