简体   繁体   中英

SQL IS NOT NULL for CASE WHEN

My current database is in the follow format,

| question_id |Tag  | Question  |
|      -      |-   --|--        -|
|1            | EN   | DOG       |
|1            | DE   | HUND      |

and i'm trying to create a result such as;

| question_id |English  | German    |
|      -      |-      --|--        -|
|1            | DOG     | HUND       |

I currently have a case when set up;

select  question_id
  , CASE WHEN tag = 'en'
               THEN text
          END AS "ENGLISH",
   CASE WHEN tag = 'de'
              THEN text
          END AS "GERMAN"
from table

The problem is because I have two case when(s), it end up returning duplicate rows

  | question_id |English  | German    |
|      -      |-      --|--        -|
|1            | NULL     | HUND       |
|1            | DOG     | NULL       |

My attempt to fix this, was to add a WHERE "ENGLISH" IS NOT NULL to the end of the statement to delete these rows, but SQL doesn't seem to recognise that case when columns are real columns.

You could use aggregation:

SELECT question_id,
       max(text) FILTER (WHERE tag = 'en') AS english,
       max(text) FILTER (WHERE tag = 'de') AS german
FROM atable
GROUP BY question_id;

you could use aggregation with case when as well

select  question_id
  , max(CASE WHEN tag = 'en'
               THEN text
          END )AS ENGLISH,
   max (CASE WHEN tag = 'de'
              THEN text
          END) AS GERMAN
from table group by question_id
CREATE TABLE test_table(question_id NUMBER,
tag VARCHAR2(10),
question VARCHAR2(10));

INSERT INTO test_table VALUES(1,'EN','DOG');
INSERT INTO test_table VALUES(1,'DE','HUND');

COMMIT;


SELECT QUESTION_ID,
MAX(CASE WHEN TAG='EN' THEN QUESTION END) AS ENGLISH,
MAX(CASE WHEN TAG='DE' THEN QUESTION END) AS GERMAN
FROM test_table
GROUP BY QUESTION_ID;

I tried the expected result for the above sample set of data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM