1

There are 3 tables as below,

table a ( eid, COLUMNA, COLUMNB, COLUMNC, COLUMND)

1001,1,1,0,1
1002,1,0,0,0




table b (id, description)
1, ABC
2, BCD
3,CDE
4,DEF

Note: description will be related to table1 columns, usually; these are checkboxes on the ui, so desciption = checkbox names from ui.

table c(eid, groupid)

My question is, I need to migrate the data from table1 into table 3 as below

1001,1
1001,2
1001,4
1002,1

Below is my query, but not getting the results as I expected.

SELECT DISTINCT eid, id
    FROM (SELECT eid,
                 CASE
                    WHEN cola = 1
                    THEN
                       (SELECT id
                          FROM tableb
                         WHERE description = 'ABC')
                    WHEN cola = 0
                    THEN
                       -1
                 END
                    AS coln_a,
                 CASE
                    WHEN colb = 1
                    THEN
                       (SELECT id
                          FROM tableb
                         WHERE description = 'BCD')
                    WHEN colb = 0
                    THEN
                       -1
                 END
                    AS coln_b,
                 CASE
                    WHEN colc = 1
                    THEN
                       (SELECT id
                          FROM tableb
                         WHERE description = 'CDE')
                    WHEN colc = 0
                    THEN
                       -1
                 END
                    AS coln_c,
                 CASE
                    WHEN cold = 1
                    THEN
                       (SELECT id
                          FROM tableb
                         WHERE description = 'DEF')
                    WHEN cold = 0
                    THEN
                       -1
                 END
                    AS coln_d
            FROM tablea
           WHERE cola = 1 OR colb = 1 OR colc = 1 OR cold= 1) temp_t,
         tableb
   WHERE coln_a = id OR coln_b = id OR coln_c = id OR coln_d = id
ORDER BY eid, id;

what is the mistake?

1
  • 1
    Can you explain your logic better? Commented Feb 24, 2017 at 4:54

1 Answer 1

1

You accomplish this by doing a series of unions:

(SELECT eid, 1 AS groupid FROM tablea WHERE COLUMNA = 1)
UNION ALL
(SELECT eid, 2 FROM tablea WHERE COLUMNB = 1)
UNION ALL
(SELECT eid, 3 FROM tablea WHERE COLUMNC = 1)
UNION ALL
(SELECT eid, 4 FROM tablea WHERE COLUMND = 1)

I don't see how the B table is related to the immediate output you want.

Sign up to request clarification or add additional context in comments.

1 Comment

Tim..Thanks a lot for the answer..it really worked..!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.