使用Oracle DECODE函数选择phone_number,在两个表中使用相同的列

时间:2017-06-16 04:19:33

标签: sql oracle decode

表:

表-A

constructor(props) {
    super(props);

    this.state = {
      'position.uniqueId': '',
      'position.company': '',
      'position.title': '',
      data: [],
      profileCandidateCollectionId: null,
      errors: {}
    };

    this.handleFormSubmit = this.handleFormSubmit.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    const profileCandidateCollection = nextProps.profileCandidate;
    const profileCandidateCollectionId = profileCandidateCollection._id;
    const careerHistoryPositions = profileCandidateCollection && profileCandidateCollection.careerHistoryPositions;
    console.log("componentWillReceiveProps: ", careerHistoryPositions);

    if (careerHistoryPositions) {
      const newData = careerHistoryPositions.map((position) =>
      ({
        'position.uniqueId': position.uniqueId || '',
        'position.company': position.company || '',
        'position.title': position.title || ''
      }));
      this.setState({
        data: newData
      })
    }
  }

  renderCareerPositions(props) {
    if(0 < this.state.data.length) {
      const careerPositions = this.state.data.map((position) =>
        <CareerPosition
          key={position.uniqueId}
          companyName={position.company}
          positionTitle={position.positionTitle}
          uniqueId={position.uniqueId}
        />
      );
      return (
        <ul>
          {careerPositions}
        </ul>
      )
    }
  }

表-B

user_id | phone_number|state|...|

条件:

  1. 必须使用Oracle DECODE函数来实现SQL语句。
  2. 如果user_id | phone_number | ...| 不为空,请使用table_b.phone_number,否则table_b.phone_number使用table_a.state=3
  3. table_a.phone_numbertable_atable_b
  4. 加入

    结果:

    选择所有user_iduser_id映射结果,如

    phone_number

3 个答案:

答案 0 :(得分:1)

为什么必须使用DECODE()?它不适合实施您的要求。 CASE()是正确的解决方案。

select a.user_id
       , case 
             -- condition 1
             when b.phone_number is not null then b.phone_number
             -- condition 2
             when a.state = 3 then a.phone_number
             -- conditions not met
             else 'no phone'
          end as phone_number
from a 
     join b on a.user_id = b.user_id  

这可以通过decode()完成,但这有多笨重?

 decode(b.phone_number
         , null
         , decode(a.state
                   , 3
                   , a.phone_number
                   , 'no phone')
         ,  b.phone_number) as phone_number

答案 1 :(得分:0)

试试这个..

select a.user_id,
      decode(b.phone_number,
             null,
             decode(a.state,
                    3,
                     a.phone_number),
      b.phone_number) phoneNumber 
     from table_a a,
          table_b b 
where a.user_id=b.user_id(+)

答案 2 :(得分:0)

将NVL与DECODE一起使用:

select a.user_id, nvl(b.phone_number, decode(a.state,3,a.phone_number,null)) phone_no from table_a a left join table_b b on a.user_id = b.user_id