2

有谁知道如何根据多列表的单列删除和合并重复项以创建“垂直摘要”。

IE) 尝试从表 A 构建表 B

Table A:
Person Language
Bob    English
Sarah  French
John   Chinese
Bob    French
Sarah  English
Sarah  Chinese

Table B (RESULT): 
Person English French Chinese 
Bob       Y       Y     (null)
Sarah     Y       Y       Y
John      (null)  (null)  Y

我最初的想法是:从数据中创建表 A,然后执行以下操作:

Create table summary as 
Select person, (case when language = 'English' then 'Y') as English, (case when        language = 'French' then 'Y') as French, (case when language = 'Chinese' then 'Y') as  Chinese
From Table A;

最后做一个选择不同的汇总表。然而,逻辑是错误的,特别是因为 distinct 在所有列中都这样做,但我只想要不同的人名。

我脑海中想到的另一个选择是创建一个表,其中仅包含不同的人名和空列英语、法语和中文。然后使用更新语句通过匹配表 A 来填充它们。

有谁知道更好的方法/我如何实现这一点。我仍处于学习 Oracle 的早期阶段(尤其是关于循环),任何帮助将不胜感激。

谢谢!

4

3 回答 3

3

Oracle 有一个解码功能

但你正在寻找的是一个支点

WITH pivot_data AS (
    SELECT Person, Language
    FROM   A
)
SELECT *
FROM   pivot_data
PIVOT (
    Count(*)        --<-- pivot_clause
    FOR Language         --<-- pivot_for_clause
    IN  ('English', 'French', 'Chinese')   --<-- pivot_in_clause
);
于 2012-07-13T11:14:20.400 回答
0

与 Sjuul 相同的想法,使用pivot,但这会为您提供所需的Y/null值:

select * from (
    select person, language, 'Y' as flag from tablea
)
pivot (max(flag) for language
    in ('English' as english, 'French' as french, 'Chinese' as chinese));

因此,要基于此创建一个新表:

create table tableb as
select * from (
    select person, language, 'Y' as flag from tablea
)
pivot (max(flag) for language
    in ('English' as english, 'French' as french, 'Chinese' as chinese));

Table created.

select * from tableb order by person;

PERSON          E F C
--------------- - - -
Bob             Y Y
John                Y
Sarah           Y Y Y

如果其中的数据tablea会发生变化,您最好制作tableb一个视图,这样它就不会失步。

于 2012-07-13T11:36:54.307 回答
0

尝试这个

Create table summary 
as  
Select 
    person, 
    min(case when language = 'English' then 'Y' end) as English, 
    min(case when language = 'French' then 'Y' end) as French, 
    min(case when language = 'Chinese' then 'Y' end) as  Chinese 
From 
    Table A
group by 
    person
于 2012-07-13T11:17:55.557 回答