sql - How do I look up row values in another table's column? -


i have table , table b

table

student     math    science 1           65      38 2           72      99 3           83      85 4           95      91 5           49      20 6           60      80 

table b

course      score_low   score_high  mark math        0           50          d math        51          80          c math        81          90          b math        91          100         science     0           50          d science     51          80          c science     81          90          b science     91          100         

what want see joining table table b

student     math    science     math mark   science mark 1           65      38          c           d 2           72      99          c           3           83      85          b           b 4           95      91                    5           49      20          d           d 6           60      80          c           c 

part of problem tablea denormalized , have separate column math , science. 1 way result unpivot data in tablea can join tableb. once have joined data based on course name , score range, can use aggregate function case expression final result in separate columns:

select a.student,   max(case when a.course = 'math' a.mark end) math,   max(case when a.course = 'science' a.mark end) science,   max(case when a.course = 'math' b.mark end) mathmark,   max(case when a.course = 'science' b.mark end) sciencemark (   select student, math mark, 'math' course    tablea   union   select student, science mark, 'science' course    tablea ) inner join tableb b   on a.course = b.course   , a.mark >= b.score_low   , a.mark <= b.score_high group a.student; 

see sql fiddle demo.

or written using multiple joins on tableb:

select a.student,   a.math,   a.science,   bmath.mark mathmark,   bsci.mark sciencemark tablea left join tableb bmath   on a.math >= bmath.score_low   , a.math <= bmath.score_high   , bmath.course = 'math' left join tableb bsci   on a.science >= bsci.score_low   , a.science <= bsci.score_high   , bsci.course = 'science'; 

see sql fiddle demo. both give result:

| student | math | science | mathmark | sciencemark | ----------------------------------------------------- |       1 |   65 |      38 |        c |           d | |       2 |   72 |      99 |        c |           | |       3 |   83 |      85 |        b |           b | |       4 |   95 |      91 |        |           | |       5 |   49 |      20 |        d |           d | |       6 |   60 |      80 |        c |           c | 

Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -