【问题标题】:Join column name with value from other table将列名与其他表中的值连接起来
【发布时间】:2017-08-04 12:12:13
【问题描述】:
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 中的列名存在于 Table2.RNVALUE 中),我只想返回 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  |
+----------------------------------+

【问题讨论】:

    标签: sql sql-server join


    【解决方案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');
    

    拥有多个具有类似名称的列表明数据模型不佳。也许这些应该在单独的行中,每行一个值。

    【讨论】:

    • 非常感谢戈登!正是我想要的!恐怕我无法更改数据模型,但这会起作用。
    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多