想象有两个表,像这样:
表1
ID | NAME | ATTR_A | ATTR_B | ATTR_C | ATTR_D
------------------------------------------------------------------
0 Bob 1 2 3 0
1 Jane 2 0 4 3
2 Richard 1 3 5 4
表2
ID | TABLE_1_FK | ATTR_E
--------------------------------
0 0 A
1 1 B
2 1 C
3 1 D
4 2 E
5 2 F
使用左联接合并表1和2,结果表将为
联接表
NAME | ATTR_E | ATTR_A | ATTR_B | ATTR_C | ATTR_D
-----------------------------------------------------------------------
Bob A 1 2 3 0
Jane B 2 0 4 3
Jane C 2 0 4 3
Jane D 2 0 4 3
Richard E 1 3 5 4
Richard F 1 3 5 4
问题
表1中的4个属性(ATTR_A,B,C,D)中的3个将始终具有大于0的值,请创建一个新表,以便如果表1中的属性具有大于0的值,则显示它在“表1 attr”列下,其值在“表1 attr_value”列下。随之创建一个新列来描述所选属性。
结果表如下:
结果
NAME | ATTR_E | "table 1 attr" | "table 1 value" | "attr description"
---------------------------------------------------------------------------------------------
Bob A ATTR_A 1 Apple
Bob A ATTR_B 2 Banana
Bob A ATTR_C 3 Carrot
Jane B ATTR_A 2 Apple
Jane B ATTR_C 4 Carrot
Jane B ATTR_D 3 Durian
Jane C ATTR_A 2 Apple
Jane C ATTR_C 4 Carrot
Jane C ATTR_D 3 Durian
Jane D ATTR_A 2 Apple
Jane D ATTR_C 4 Carrot
Jane D ATTR_D 3 Durian
Richard E ATTR_A 1 Apple
Richard E ATTR_B 3 Banana
Richard E ATTR_C 5 Carrot
Richard E ATTR_D 4 Durian
Richard F ATTR_A 1 Apple
Richard F ATTR_B 3 Banana
Richard F ATTR_C 5 Carrot
Richard F ATTR_D 4 Durian
答案 0 :(得分:0)
您需要UNPIVOT
个加入结果。我发布的工作示例与您的问题完全相同,因此您将其替换为表,并在sql注释中进行了说明。
SELECT *
FROM
(
-- your join result here...
SELECT 1 col_id, 2 col_attrib_a, 0 col_attrib_b FROM dual UNION
SELECT 9 col_id, 0 col_attrib_a, 7 col_attrib_b FROM dual
)
UNPIVOT
(
value
FOR value_type IN (col_attrib_a, col_attrib_b) -- the name of the attrib columns here...
)
WHERE 1=1
AND value > 0
;