简体   繁体   English

SQL查询-别名+不同时期+不同表

[英]SQL Query - aliasing + different periods + different tables

I am using toad for oracle and I experienced different issues.我正在为 oracle 使用蟾蜍,我遇到了不同的问题。

Aliasing - When I want to use the same column twice?!别名 - 当我想两次使用同一列时?!
Let us asume that we have a table x which has col1, col2, col3.假设我们有一个表 x,其中包含 col1、col2、col3。 Col1 contains a customer contact numbers (211,212,213, and more) Col1 包含客户联系电话(211,212,213 等)

And there is another table, y , that has col1,col4,col5.还有另一个表y ,它有 col1,col4,col5。 Col1 in both tables are equal.两个表中的 Col1 相等。 Col4 shows whether a number is main or secondary. Col4 显示一个数字是主要的还是次要的。

Table yy

(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)您没有说 col2 是什么,但是您从同一张表的同一行中获取同一列(col1)并尝试为其分配不同的含义(main_number 和 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如果 COL1 在 'y' 上是唯一的,那么它只能是主要的或次要的,所以这应该有效

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如果 COL1 在 'y' 上不是唯一的,那么它可以是主要的和次要的,所以这应该有效

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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