如何在旋转数据时编写 case 表达式

How to write case expression while pivoting the data

CREATE TABLE details_1 (
    e_id    NUMBER(10),
    e_name  VARCHAR2(30),
    CONSTRAINT pk_details_1_e_id PRIMARY KEY ( e_id )
);

insert into details_1 values(11,'A');


CREATE TABLE ques_ans (
    ques_ans_id  NUMBER(10),
    ref_ques_id  NUMBER(10),
    ref_ans_id   NUMBER(10),
    ref_ans_value VARCHAR2(100),
    e_id         NUMBER(10),
    CONSTRAINT pk_ques_ans PRIMARY KEY ( ques_ans_id ),
    CONSTRAINT fk_ques_ans FOREIGN KEY ( e_id )
        REFERENCES details_1 ( e_id ),
        constraint fk_ques_and_ques_id foreign key(ref_ques_id)
        references ques_ref (ques_id)
);

insert into ques_ans values(1,3,1,11,null);
insert into ques_ans values(2,2,2,11,null);
insert into ques_ans values(3,4,1,11,null);
insert into ques_ans values(4,23,1,11,11);

CREATE TABLE ques_ref (
    ques_id     NUMBER(10),
    code        VARCHAR2(50),
    code_label  VARCHAR2(100),
    constraint pk_ques_ref primary key(ques_id)
);

insert into ques_ref values(3,'changes_exist','Any known changes');
insert into ques_ref values(2,'E_Clubbed','E_id clubbed with other');
insert into ques_ref values(4,'E_impacted','E impacted by other');
insert into ques_ref values(23,'E_Clubbed_with_other','E clubbed with other E');

CREATE TABLE ans_ref (
    ref_ans_id  NUMBER(10),
    code        VARCHAR2(10),
    code_value  VARCHAR2(30)
);

insert into ans_ref values(1,'R_Yes','Yes');
insert into ans_ref values(2,'R_No','No');

commit;

My Attempt :

select  d.e_id,
        max(case qa.ref_ques_id when 3 then ar.code_value end) changes_exist,
        max(case qa.ref_ques_id when 2 then ar.code_value end) E_Clubbed,
        max(case qa.ref_ques_id when 4 then ar.code_value end) E_impacted,
--need to write case expression here
  from      details_1 d
        join
            ques_ans qa
          on d.e_id = qa.e_id
        join ans_ref ar
          on ar.ref_ans_id = qa.ref_ans_id
  group by d.e_id

我遇到了以下要求:

我需要检查 ques_ans table 的 ref_ques_id 是否为 23 那么它应该从同一个 table 显示 ref_ans_valueques_ans

例如: 在 table ques_ans 中,对于 ques_ans_id 4 ref_ques_id 是 23 那么在这种情况下它将显示 ref_ans_value 即 11 在列 ref_ans_value

如何在旋转数据时编写 case 表达式?我想知道我们是否可以使用 case 表达式来做到这一点,或者有没有其他方法可以做到这一点?

预期输出:

+------+---------------+-----------+------------+------------------+
| E_ID | CHANGES_EXIST | E_CLUBBED | E_IMPACTED | E_CLUBBED_WITH_E |
+------+---------------+-----------+------------+------------------+
|   11 | Yes           | No        | Yes        |               11 |
+------+---------------+-----------+------------+------------------+

您可以通过进一步聚合来实现。

CASE
    WHEN MAX(ques_ans.ref_ques_id) = '23' THEN MAX(COALESCE(ques_ans.ref_ans_value, 0))
    ELSE -4
END

您需要解决两个问题:

1

您在 SELECT 子句中人为地汇总了内容以防止技术问题,但您可能需要更改此设置,具体取决于您的实际数据看起来如何(不是问题中显示的,但实际上).如果您有不同参考的答案,那么您可能想要更改数据库结构以更好地反映现实。

2

你没有告诉我们当 ques_id 的值为 NOT 23 时会发生什么,所以我在 ELSE.您需要将其更改为您实际需要的。