[英]Combine master and detail table into one row by combining detail fields
I have 2 tables, one which is the master the other the details. 我有2张桌子,一张是主人,另一张是细节。 They have a 1 to many relationship:
他们有一对多的关系:
MasterTable
------------
id (pk)
col1
DetailTable
------------
id (pk)
mid (fk to MasterTable id)
col1
An example of how data would look would be as such: 数据外观的示例如下:
MasterTable
ID
---
1
2
3
4
5
DetailTable
ID | MID | COL1 |
---|-------|-------|
1 1 BIRD
2 1 DOG
3 1 DOG --Duplicates are allowed for the same MID
4 1 CAT
5 2 CAT
6 5 FISH
For the detail table the possible values for col1 are: 对于明细表,col1的可能值为:
I then need to create a query which will layout for each id in the master table to see if they have any of these values. 然后,我需要创建一个查询,该查询将对主表中的每个id进行布局,以查看它们是否具有这些值中的任何一个。 So the final query result would look like this:
因此,最终查询结果将如下所示:
MasterID | BIRD | DOG | CAT | FISH | MOUSE
-----------------------------------------------------
1 Y Y Y
2 Y
3
4
5 Y
So I am collapsing the detail table into one row in the final result. 因此,我将详细信息表折叠为最终结果中的一行。 I am unsure how to create this query though.
我不确定如何创建此查询。
I was trying something like this, but it doesn't work: 我正在尝试类似的方法,但是它不起作用:
SELECT MASTERTABLE.ID,
CASE WHEN DETAILTABLE.col1 = 'BIRD' THEN 'Y' ELSE NULL END AS BIRD,
CASE WHEN DETAILTABLE.col1 = 'DOG' THEN 'Y' ELSE NULL END AS DOG,
CASE WHEN DETAILTABLE.col1 = 'CAT' THEN 'Y' ELSE NULL END AS CAT,
CASE WHEN DETAILTABLE.col1 = 'FISH' THEN 'Y' ELSE NULL END AS FISH,
CASE WHEN DETAILTABLE.col1 = 'MOUSE' THEN 'Y' ELSE NULL END AS MOUSE
FROM MASTERTABLE LEFT JOIN DETAILTABLE ON MASTERTABLE.ID = DETAILTABLE.mid;
Pivoting, whether it is done with the PIVOT
operator (starting from Oracle version 11.1) or with conditional aggregation (version 10.2 or earlier), works equally well on any set of rows, whether that is a single table, the result of joining two tables, or the result of any other set operation permitted in SQL (another aggregation, a UNION ALL
, or anything else). 无论是使用
PIVOT
运算符(从Oracle版本11.1开始)还是使用条件聚合(版本10.2或更早版本)进行数据透视,该PIVOT
在任何行集合(无论是单个表还是联接两个表的结果)上均能很好地工作,或SQL中允许的任何其他设置操作的结果(另一种聚合, UNION ALL
或其他任何方式)。
You were pretty close in your attempt. 您的尝试非常接近。 All you have to do is to
GROUP BY MASTERTABLE.ID
(since you want only one row per MASTERTABLE.ID
) and to take the MAX
of all those CASE
expressions: if at least one of them is 'Y'
then the MAX
is 'Y'
, otherwise it is NULL
. 您所需要做的就是
GROUP BY MASTERTABLE.ID
(因为每个MASTERTABLE.ID
只想要一行),并取所有这些CASE
表达式的MAX
:如果其中至少一个是'Y'
则MAX
是'Y'
,否则为NULL
。
So: 所以:
In your query, EXACTLY AS IT IS, 在您的查询中,按原样,
CASE .... END as BIRD
to MAX(CASE ... END) as BIRD
CASE .... END as BIRD
更改为MAX(CASE ... END) as BIRD
GROUP BY MASTERTABLE.ID
at the end GROUP BY MASTERTABLE.ID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.