2017-08-04 41 views
1
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 

如果Table1中的值大於0(Table1.RNVALUE中存在Table1中的列名),我只希望返回Table2中的id。所以在這種情況下,我只想讓table2的前兩行彈出,因爲它們在table1中的值大於0.任何人都可以通過查詢來幫助我做到這一點?使用其他表中的值加入列名稱

表1:

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

表2:

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

回答

1

我相信你想是這樣的:

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'); 

擁有多個列其名稱一樣,表明較差的數據模型。也許這些應該在不同的行中,每行一個值。

+0

謝謝戈登!正是我在找什麼!恐怕我不能改變數據模型,但這會起作用。 – Wessel

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 
相關問題