Join column name with value from other table

时间:2017-08-04 12:12:14

标签: sql sql-server join

SELECT id FROM Table2 t2
       INNER JOIN Table1 t1
           on t1.ordno = t2.ordno
           and t1.testcode = t2.testcode
       WHERE RN1 > 0
       AND   RN2 > 0
       AND   RN3 > 0
       AND   RN3 > 0
       AND   RN4 > 0
       AND   RN5 > 0
       AND   RN6 > 0

I only want to return the id from Table2 if a value from Table1 is >0 (column name from Table1 exists in Table2.RNVALUE). So in this case, I only want the first two rows of table2 to pop-up because they have a value in table1 which is greater then 0. Can anyone help me with a query to do this?

Table1:

+--------------------------------------------------------+
| ORDNO | TESTCODE | RN1 | RN2 | RN3 | RN4 | RN5  | RN6  |
+--------------------------------------------------------+
| 123   | 456      | 55  | 56  | 0   | 0   | null | null |
+--------------------------------------------------------+

Table2:

+----------------------------------+
| ORDNO | TESTCODE | RN_VALUE | ID |
+----------------------------------+
| 123     456        RN1        1  |
| 123     456        RN2        2  |
| 123     456        RN3        3  |
| 123     456        RN4        4  |
+----------------------------------+

2 个答案:

答案 0 :(得分:1)

I believe you want something like this:

SELECT t2.*
FROM Table2 t2 INNER JOIN
     Table1 t1
     ON t1.ordno = t2.ordno AND t1.testcode = t2.testcode
WHERE (RN1 > 0 AND t2.RN_VALUE = 'RN1') OR
      (RN2 > 0 AND t2.RN_VALUE = 'RN2') OR
      (RN3 > 0 AND t2.RN_VALUE = 'RN3') OR
      (RN4 > 0 AND t2.RN_VALUE = 'RN4') OR
      (RN5 > 0 AND t2.RN_VALUE = 'RN5') OR
      (RN6 > 0 AND t2.RN_VALUE = 'RN6');

Having multiple columns with names like that suggests a poor data model. Perhaps these should be in separate rows, with one value per row.

答案 1 :(得分:0)

select t2.*
from table2 t2
inner join (select ordno, testcode, 1 as rn, rn1 as val
            union
            select ordno, testcode, 2 as rn, rn2 as val
            union
            select ordno, testcode, 3 as rn, rn3 as val
            union
            select ordno, testcode, 4 as rn, rn4 as val
            union
            select ordno, testcode, 5 as rn, rn5 as val
            union
            select ordno, testcode, 6 as rn, rn6 as val
           ) t1
on t2.rn_value=t1.rn
and t2.ordno=t1.ordno
and t2.testcode=t1.testcode
where t1.val>0