create table item (id number not null, item_name varchar2(200) not null);
create table color (id number not null, color_name varchar2(200) not null);
create table item_color (item_id number not null, color_id number not null);
insert into item values (1, 'item 1');
insert into item values (2, 'item 2');
insert into item values (3, 'item 3');
insert into color values (1, 'red');
insert into color values (2, 'blue');
insert into color values (3, 'green');
insert into item_color values (1, 1);
insert into item_color values (1, 3);
insert into item_color values (2, 2);
insert into item_color values (2, 3);
insert into item_color values (3, 2);
commit;
然后选择:
select * from
(
select
i.item_name
, c.color_name
from
item i
, color c
, item_color ic
where
ic.item_id = i.id
and ic.color_id = c.id
) pivot (
count(color_name) cnt
for color_name in ('red', 'blue', 'green')
);
给出:
万一
item 1 1 0 1
item 2 0 1 1
item 3 0 1 0
你不知道的颜色列表事先你可以先选择颜色表,然后构建支点动态选择(像for color_name in (select color_name from color)
这样的子选择是不可能的),或者可以使用pivot xml
并对结果进行后处理:
select * from
(
select
i.item_name
, c.color_name
from
item i
, color c
, item_color ic
where
ic.item_id = i.id
and ic.color_id = c.id
) pivot xml (
count(color_name) cnt
for color_name in (any)
)
给出:
item 1 <PivotSet><item><column name = "COLOR_NAME">green</column><column name = "CNT">1</column></item><item><column name = "COLOR_NAME">red</column><column name = "CNT">1</column></item></PivotSet>
item 2 <PivotSet><item><column name = "COLOR_NAME">blue</column><column name = "CNT">1</column></item><item><column name = "COLOR_NAME">green</column><column name = "CNT">1</column></item></PivotSet>
item 3 <PivotSet><item><column name = "COLOR_NAME">blue</column><column name = "CNT">1</column></item></PivotSet>
@rexem:我如何去分组结果,使每个item_name只出现一次,每个颜色“指示符”出现在同一行? (以我的问题中的所需输出为例) – 2009-09-01 18:31:56
@Colin:更新了答案。 – 2009-09-01 18:43:45
@rexem:非常感谢您的全面回答。这产生了我所希望的。 我不得不在每个“END”之后和每个“MAX()”之后删除字符串周围的括号,因为我在TOAD中出错。任何想法为什么? 再次感谢您的帮助。 – 2009-09-01 21:34:59