简体   繁体   中英

SQL Query - aliasing + different periods + different tables

I am using toad for oracle and I experienced different issues.

Aliasing - When I want to use the same column twice?!
Let us asume that we have a table x which has col1, col2, col3. Col1 contains a customer contact numbers (211,212,213, and more)

And there is another table, y , that has col1,col4,col5. Col1 in both tables are equal. Col4 shows whether a number is main or secondary.

Table y

(Col1,col4,col5)
(211,Main,v)
(212,Secondary,s)
(213,Secondary,w)

What I want to do is as follow:

SELECT col2, col1 as mainNumbet, col1 as secondNumber
  FROM x
 WHERE mainNumber IN (SELECT col1 
                        FROM y 
                       WHERE col4 = 'main')
   AND SecondNumber IN (SELECT col1 
                          FROM y 
                         WHERE col4 = "secondary")

But it states that there is a problem???

There are several problems with your code.

Perhaps this is what you want:

SELECT x.col2, 
       CASE WHEN col4 ='main'      THEN x.col1 END AS mainNumber,
       CASE WHEN col4 ='secondary' THEN x.col1 END AS secondNumber, 
FROM x
  JOIN y
    ON x.col1 = y.col1

You don't say what col2 is, but you are taking the same column (col1) from the same row of the same table and trying to assign different meanings to it (main_number and second_number)

SELECT col2, col1 as mainNumbet, col1 as secondNumber
  FROM x

If COL1 is unique on 'y', then it can only be the main OR the secondary, so this should work

SELECT col2, col1 as number, (select col4 from y where y.col1=x.col1) type
  FROM x

If COL1 is NOT unique on 'y', then it can be a main and a secondary, so this should work

SELECT col2, col1 as number, 
  (select col4 from y where y.col1=x.col1 and col4 = 'main' and rownum=1) m_ind,
  (select col4 from y where y.col1=x.col1 and col4 = 'secondary' and rownum=1) s_ind
FROM x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM