gpt4 book ai didi

Oracle sql 查询 : pivot table with dynamicly filled for in (advanced)

转载 作者:行者123 更新时间:2023-12-04 05:09:15 26 4
gpt4 key购买 nike

我需要展平一个表,但这里是棘手的部分,clomuns 是动态的,当添加包含新 ID 的新记录时,查询应该可以工作。

这是我的工作查询(简化了 IN 这实际上是数百个值):

SELECT *
FROM (select qv.respnr, sq.question_id, qv.question_value
from survey_question sq, question_values qv
where qv.question_id = sq.question_id
and sq.survey_id = 1
order by qv.respnr, page, ranked)
PIVOT (
MAX(question_value) --<-- pivot_clause
FOR question_id --<-- pivot_for_clause
IN (346 as c346,347 as c347)
)

我要更换 IN (346 as c346,347 as c347)像这样:
SELECT mq.question_id
FROM meta_question mq, survey_question sq2
WHERE sq2.survey_id = 1
AND mq.question_id = sq2.question_id
ORDER BY page, ranked

知道如何做到这一点吗?

我注意到 IN 不能简单地用 select 语句归档,所以这不起作用:
IN (SELECT mq.question_id
FROM meta_question mq, survey_question sq2
WHERE sq2.survey_id = 1
AND mq.question_id = sq2.question_id
ORDER BY page, ranked)

最佳答案

SQL中所有列的名称和类型需要在编译时知道,这里你必须使用dynamic SQL因为您希望根据数据更改列数。

如果你使用 PL/SQL,你可以使用 ref cursor :

DECLARE
l_rc SYS_REFCURSOR;
l_dynamic_query VARCHAR2(32000);
BEGIN
FOR cc IN (SELECT mq.question_id
FROM meta_question mq, survey_question sq2
WHERE sq2.survey_id = 1
AND mq.question_id = sq2.question_id
ORDER BY page, ranked) LOOP
-- build dynamic query here
END LOOP;
OPEN l_rc FOR '
SELECT *
FROM (SELECT qv.respnr, sq.question_id, qv.question_value
FROM survey_question sq, question_values qv
WHERE qv.question_id = sq.question_id
AND sq.survey_id = 1
ORDER BY qv.respnr, page, ranked)
PIVOT ( MAX (question_value) --<-- pivot_clause
FOR question_id --<-- pivot_for_clause
IN (' || l_dynamic_query || ')
)';
-- process l_rc (LOOP..FETCH..CLOSE)
END;

您也可以使用 DBMS_SQL .

关于Oracle sql 查询 : pivot table with dynamicly filled for in (advanced),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15092625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com