0

我有一张这样的桌子:

+-------+-------+-------+-------+
|  ID   | City  | Param | Value |
+-------+-------+-------+-------+
| id1   | city1 | a     | value |
| id2   | city1 | b     | value |
| id3   | city1 | c     | value |
| id4   | city2 | a     | value |
| id5   | city2 | b     | value |
| id6   | city2 | c     | value |
| ...   | ...   | ...   | ...   |
| idN   | cityN | a     | value |
| idN+1 | cityN | b     | value |
| idN+2 | cityN | c     | value |
+-------+-------+-------+-------+

如您所见,它为每个城市都有一个子表,例如:

+-------+-------+
| Param | Value |
+-------+-------+
| a     | value |
| b     | value |
| c     | value |
+-------+-------+

所以我想加入所有子表并得到一个这样的表:

+-------+-------+-------+-----+-------+
| Param | city1 | city2 | ... | cityN |
+-------+-------+-------+-----+-------+
| a     | value | value | ... | value |
| b     | value | value | ... | value |
| c     | value | value | ... | value |
+-------+-------+-------+-----+-------+

任何想法我怎么能得到它?

先感谢您!

注1:城市数量不定。

注意 2:解决方案可以是 PL/SQL 函数。

4

2 回答 2

1

为了获得您想要的结果,您需要对数据进行透视。虽然您说 plsql 可能是一个选项,但您没有指定您使用的 Oracle 版本。从 Oracle 11g 开始,该PIVOT功能可用。

如果您不使用 Oracle 119,则可以使用带有CASE表达式的聚合函数:

select param,
    max(case when city = 'city1' then value end) City1,
    max(case when city = 'city2' then value end) City2
from yourtable
group by param

请参阅SQL Fiddle with Demo

由于您声明您将拥有未知数量的city值,因此您将需要创建此查询的动态 sql 版本。您可以创建类似于此的过程:

CREATE OR REPLACE procedure dynamic_pivot(p_cursor in out sys_refcursor)
as
    sql_query varchar2(1000) := 'select param ';

    begin
        for x in (select distinct city from yourtable order by 1)
        loop
            sql_query := sql_query ||
                ' , max(case when city = '''||x.city||''' then value else null end) as '||x.city;

                dbms_output.put_line(sql_query);
        end loop;

        sql_query := sql_query || ' from yourtable group by param order by param';
        dbms_output.put_line(sql_query);

        open p_cursor for sql_query;
    end;
/

然后要得到你的结果,你可以使用以下(注意:我在 TOAD 中使用了这个):

variable x refcursor
exec dynamic_pivot(:x)
print x

您的查询结果将是:

| PARAM | CITY1 | CITY2 |
-------------------------
|     a | value | value |
|     b | value | value |
|     c | value | value |
于 2013-02-15T17:02:29.330 回答
0

如果你有 10G,你可以使用 new pivotin 11G 或model从句。检查文档。

于 2013-02-15T21:17:54.587 回答