2013-03-20 31 views
0

我有2代表这样行作为列的sql

表1

profile 
-------- 
id 
--- 
1 | XXX 
2 | zzz 

表2

profile_details 
----------------- 
id | K  | V 
--------------------------- 
1 | first_name | XXX 
1 | last_name | YYY 
1 | gender  | female 
2 | name  | zzzzz 
2 | gender  | male 
2 | phone  | 8999xxxx 
2 | location | india 
2 | spoken_language | hindi 

我使用此查询来获取行作为COLS

select profiles.id, 
max(decode(k, 'first_name', v, NULL)) first_name, 
max(decode(k, 'last_name', v, null))as last_name , 
max(decode(k, 'gender', v, NULL)) gender 
from profile_details , profiles 
where 
profile_details.id = profiles.id 
and 
profile_details.id=1 
group by profiles.id 

抓到我

id | first_name| last_name | gender 
-------------------------------------------- 
1 | XXX  | YYY  | female 

这可以将行作为列提取。但是如何将此查询更改为动态包含列,因为K值可能是任何可能的值。

前,为ID 2,它应该是

id | name | gender | mobile | location | spoken_language 
------------------------------------------------------------------ 
2 | zzz | male | 8999xxxx | india  | hindi 

感谢 V

+2

你的问题的简单答案是“不”。 SQL语句必须明确列出正在返回的列。扩展的答案是:你知道关于动态SQL的任何信息吗? – 2013-03-20 13:49:21

+0

我不知道:-( – 2013-03-20 14:36:23

回答

1

您可以使用动态SQL生成要执行的字符串。

在Oracle中,我将使用一个过程,可以将必要的id值传递给我,然后返回sys_refcursor

的过程将类似于以下内容:

CREATE OR REPLACE procedure dynamic_pivot_profile(p_cursor in out sys_refcursor, p_id in number) 
as 
    sql_query varchar2(1000) := 'select p.id '; 

    begin 
     for x in (select distinct k from profile_details where id=p_id order by 1) 
     loop 
      sql_query := sql_query || 
       ' , max(case when pd.k = '''||x.k||''' then pd.v end) as "'||x.k||'"'; 

       dbms_output.put_line(sql_query); 
     end loop; 

     sql_query := sql_query || ' from profile p 
               inner join profile_details pd 
                on P.ID = pd.id 
               where PD.ID = '||p_id||' 
               group by p.id'; 
     dbms_output.put_line(sql_query); 

     open p_cursor for sql_query; 
    end; 
/

然后返回结果,我用蟾蜍如下:

variable x refcursor 
exec dynamic_pivot_profile(:x, 1) -- pass in your id 
print x 

这将返回您提供所需的结果。

+0

如果数据量很大,这个查询的性能如何? – 2013-03-22 06:01:21

+0

@ user1353364任何时候当你尝试转换一个巨大的数据量时,你都会遇到性能问题,这就是为什么这种类型的数据表示应该在应用程序的表示层中完成,而不是在SQL代码中完成。另外,您还需要确保在表上有适当的索引。 – Taryn 2013-03-22 10:27:09

2

你这里有什么是实体 - 属性 - 值模式,通常用于在架构提供了灵活性。

不足之处在于,从现在开始你所做的每件事都会带来无法忍受的痛苦和困难,包括这一点,对此,没有简单的解决方案。

下面是对这个问题的教训:https://www.simple-talk.com/opinion/opinion-pieces/bad-carma/