简体   繁体   English

使用SQL将相关表展平为多列

[英]Flatten a related table into a multiple columns with SQL

I'm trying to exact data from two tables in an IFS database (Oracle backend) using SQL. 我正在尝试使用SQL从IFS数据库(Oracle后端)的两个表中提取数据。 One table contains a list of Addresses, the other contains the Types those addresses have. 一个表包含一个地址列表,另一个表包含那些地址具有的类型。

Example: 例:

Address table: 地址表:

Address1
Address2

AddressType table AddressType

Address1, DELIVERY, TRUE
Address1, DOCUMENT, FALSE
Address1, PAY, FALSE
Address2, DELIVERY, FALSE
Address2, PAY, TRUE

I can write a query that successfully gets the addresses, and their types, but I end up with a new row for every address type (essentially it just looks like the AddressType table). 我可以编写一个查询来成功获取地址及其类型,但是最后我为每种地址类型添加了一个新行(本质上看起来就像AddressType表一样)。

SELECT 
    a.address_ID,
    at.address_type,
    at.address_type_default_b
FROM
    addresses a,
    address_type at
WHERE
    a.address_ID = at.address_ID

What I want is a query that will 'flatten' the table, move each type into a column. 我想要的是一个查询,它将“展平”表,将每种类型移动到列中。 Based on the above example, the resulting table would have 2 rows, with 4 columns, see below. 根据上面的示例,结果表将具有2行,4列,请参见下文。

Desired result 所需结果

Address1, TRUE, FALSE, FALSE
Address2, FALSE,*NULL*,TRUE

Note that I don't care what goes in for Null, blank, NA or NULL 请注意,我不在乎Null,空白,NA或NULL的含义

Any help would be much appreciated. 任何帮助将非常感激。 I realize I could do this in excel, but with the size of the data and the number of times I'll have to do this, it would be nice to do this in SQL. 我意识到我可以在excel中完成此操作,但是由于数据的大小和必须执行此操作的次数,在SQL中执行此操作会很不错。

Sorry about the poor formatting of the question... I can't figure out how to insert tables or get my sql to look correct. 抱歉,问题的格式不正确...我无法弄清楚如何插入表格或使我的sql看起来正确。

Assuming you have only 3 statuses for an address and each status can happen only once: 假设一个地址只有3个状态,并且每个状态只能发生一次:

In case you won't have any value, it will return null as desired 如果您没有任何值,它将根据需要返回null

select a.address_ID,max( case when address_type='Delivery' then address_type_default_b end  ) 
,max( case when address_type='Document' then address_type_default_b end  )
,max( case when address_type='Pay' then address_type_default_b end  )
from address_table a
left join addresstype_table at on a.address_ID=b.address_ID
group by a.address_ID

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

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