简体   繁体   中英

Create view from 3 tables

I have 3 tables.

table1

id info1 info2
1  a     b
2  a     b
3  a     b
4  a     b

table2

id table1_id column_id value
1  1         1      10
2  1         2      20
3  1         3      30
4  2         1      40
5  2         2      50
6  2         3      60
7  3         1      70
8  3         2      80
9  3         3      90
10  4         1      100
11  4         2      110
12  4         3      120

table3

column_id column
1         column1
2         column2
3         column3

Based on the above, I need to create a view which would convert rows to columns in the following way:

column1 column2 column3
10      20      30
40      50      60
70      80      90
100     110     120

Is it possible to create a view like the above?

You can use below if you use oracle 11g or above you can use pivot also.

SELECT max(CASE 
                WHEN column1 = 'column1'
                    THEN value1
                END) column1
        ,max(CASE 
                WHEN column1 = 'column2'
                    THEN value1
                END) column2
        ,max(CASE 
                WHEN column1 = 'column3'
                    THEN value1
                END) column3
    FROM (
        SELECT t2.table1_id
            ,t3.column1
            ,to_char(t2.value1) AS value1
        FROM table2 t2
        JOIN table1 t1 ON t1.id1 = t2.table1_id
        JOIN table3 t3 ON t3.column_id = t2.column_id
        )
    GROUP BY table1_id

The short answer to the question is yes, a solution to the problem could be to join the tables and then pivot them.

I have written some code as a suggestion to help you along, this is untested code and you will have to tweak it a bit

 select * from (
       select T1.id as Row, T3.column, T2.value
       from table1 T1
        left join table2 T2 on T2.table1_id = T1.id
        left join table3 T3 on T3.column_id = T2.column_id

    )
    pivot 
    (
       sum(value)
       for value in ('column1','column2','column3')
    )
    group by row
    order by row

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