如果细节不足,我会尽量详细解释这个问题,请帮助编辑我的问题或查询我缺少的细节。
问题说明
我需要编写一个SELECT语句,将转换 ORDERED_BY 中的数据从REQUESTED_AUTHORS表转换为 AUTHOR_NAME 数据。例如, JDER 如 ORDERED_BY 必须转换到 Jack Johnson ,如 AUTHOR_NAME所示< / strong>即可。因此,最终结果将是杰克约翰逊而不是 JJ 。下面显示了我的2个表:
REQUESTED_AUTHORS
+-----------+
| ORDERED_BY|
+-----------+
| JJ |
+-----------+
| AB |
+-----------+
| JonJey |
+-----------+
| Admin |
+-----------+
| Tech Assit|
+-----------+
| Dr.Ob |
+-----------+
| EL |
+-----------+
| TA |
+-----------+
| JD |
+-----------+
| ET |
+-----------+
AUTHOR_LIST
+----------------+---------------------+
| ORDER_INITIAL | AUTHOR_NAME |
+----------------+---------------------+
| JJ | Jack Johnson |
+----------------+---------------------+
| AB | Albert Bently |
+----------------+---------------------+
| AlecBor | Alec Baldwin |
+----------------+---------------------+
| KingSt | KingSton |
+----------------+---------------------+
| GaryNort | Gary Norton |
+----------------+---------------------+
| Prof.Li | Professor Li |
+----------------+---------------------+
| EL | Elton Langsey |
+----------------+---------------------+
| TA | Thomas Alecson |
+----------------+---------------------+
| JD | Johnny Depp |
+----------------+---------------------+
| ET | Elson Tarese |
+----------------+---------------------+
解决方案尝试(1)
SELECT ru.*, al.AUTHOR_NAME
FROM REQUESTED_AUTHORS ru, AUTHOR_LIST al
WHERE al.ORDER_INITIAL = ru.ORDERED_BY;
但这并不像我预期的那样有效,因为ORDERED_BY和ORDER_INITIAL都有不同的数据。我尝试使用DECODE函数来转换它,但我被困在那里。
解决方案尝试(2)
SELECT ru.ORDERED_BY,
al.ORDER_INITIAL,
DECODE(ru.ORDERED_BY, (ru.ORDERED_BY != al.ORDER_INITIAL), ru.ORDERED_BY,
(ru.ORDERED_BY = al.ORDER_INITIAL), al.AUTHOR_NAME)results
FROM REQUESTED_AUTHORS ru, AUTHOR_LIST al;
我打算做的是改变数据与其他数据类似,但保留不同的数据。
意味着下面显示的数据保持不变并且没有转换,因为没有任何内容可以转换为。
+-----------+
| ORDERED_BY|
+-----------+
| JonJey |
+-----------+
| Admin |
+-----------+
| Tech Assit|
+-----------+
| Dr.Ob |
+-----------+
我的问题:
如何编写查询以转换类似数据并保留不同数据?
答案 0 :(得分:4)
您需要外部联接(避免旧式联接的另一个原因):
SELECT ru.*,
-- if there's a match return AUTHOR_NAME, otherwise keep ORDERED_BY
COALESCE(al.AUTHOR_NAME, ru.ORDERED_BY)
FROM REQUESTED_AUTHORS ru
LEFT JOIN AUTHOR_LIST al
ON al.ORDER_INITIAL = ru.ORDERED_BY;
答案 1 :(得分:1)
在这里使用左外连接
SELECT ru.*, nvl( al.AUTHOR_NAME , ru.ordered_by)
FROM REQUESTED_AUTHORS ru, AUTHOR_LIST al
WHERE ru.ORDERED_BY = al.ORDER_INITIAL(+);