简体   繁体   English

Oracle SQL:使用相同的别名在对 select 的 CASE 语句中,在一种情况下为一列,在其他两列和另外三列具有相同的别名

[英]Oracle SQL: Using same alias In CASE statement to select in one case one column, in the other two columns and another three with the same alias

I am doing something wrong in a select with cases in Oracle and I'll appreciate the help from the stackoverflow community.我在 select 和 Oracle 案例中做错了什么,我将感谢 stackoverflow 社区的帮助。

What I am trying to do is based on a condition (value of a column) to return one or multiple columns.我想要做的是基于一个条件(一列的值)来返回一个或多个列。

I always need my query to return three columns: Article, Paragraph, Sub_Paragraph我总是需要我的查询返回三列:文章、段落、子段落

If the value of a column list_value which I am checking is Article, then I only need to return the Article and null to both Paragraph and Sub Paragraph.如果我正在检查的列list_value的值为Article,那么我只需将Article和null返回到Paragraph和Sub Paragraph。 If the value of a column is Paragraph, I need to return both paragraph and article and the Sub_Paragraph should be null.如果列的值为段落,我需要返回段落和文章,并且 Sub_Paragraph 应该是 null。 If the value of a column is Sub_Paragraph, I need to return all values for article, paragraph and Sub_Paragraph.如果某列的值为 Sub_Paragraph,我需要返回文章、段落和 Sub_Paragraph 的所有值。

SELECT

     CASE
         WHEN att.list_value = 'Sub_Paragraph' THEN att.column_with_subpar_value
     END AS sub_paragraph,
     CASE
         WHEN att.list_value = 'Sub_Paragraph' THEN att.column_with_par_value
     END AS paragraph,
     CASE
         WHEN att.list_value = 'Sub_Paragraph' THEN att.column_with_article_value
     END AS article,
   
     CASE
         WHEN att.list_value = 'Paragraph' THEN att.column_with_par_value
     END AS paragraph,
     CASE
         WHEN att.list_value = 'Paragraph' THEN att.column_with_article_value
     END AS article,
  
     CASE
         WHEN att.list_value = 'Article' THEN att.column_with_article_value
     END AS article
  
 FROM
     att
     
 WHERE
     id = 1

but with this approach I am getting column like article_1, article_2 etc. What's the best way to succeed it?但是通过这种方法,我得到了 article_1、article_2 等专栏。成功的最佳方法是什么?

Looking at your requirement, hope below is what you are expecting.查看您的要求,希望下面是您所期望的。

SELECT CASE
         WHEN att.list_value = 'Sub_Paragraph' THEN
          att.column_with_subpar_value
       END AS sub_paragraph,
       CASE
         WHEN att.list_value in ('Sub_Paragraph', 'Paragraph') THEN
          att.column_with_par_value
       END AS paragraph,
       CASE
         WHEN att.list_value in ('Sub_Paragraph', 'Paragraph', 'Article') THEN
          att.column_with_article_value
       END AS article
  FROM att
 WHERE id = 1;

One of the approaches on how this can be resolved would be to concatenate all the columns into one column with a known separator, which can be split later into the desired set of columns.解决此问题的方法之一是将所有列连接到一个具有已知分隔符的列中,稍后可以将其拆分为所需的列集。

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

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