1

I am trying to have a new column using case query but i also wanted to use it in my other case query as shown below, i am unable to execute the query below . Please give your opinion. Thanks

    select

    case  when ccis.id  is not null then 'High'
    else null 
    end as category,
    
    case  
    when category is not NULL then True
    else False 
    end as flag



    FROM "view1" as ccis left outer join "view2" as cctm 
    on ccis.study_name = cctm.study_name 


    from goes here ---
    Join  statement goes here ---
4
  • Tag your question with the database you are using. As a general rule in SQL, you cannot use a column alias defined in the select in expressions in the same select (or where or from for that matter). Commented Jul 29, 2020 at 15:15
  • Is the query exactly as shown? Because you have an extra comma and you're missing FROM Commented Jul 29, 2020 at 15:17
  • I fixed it sorry @oso Commented Jul 29, 2020 at 15:18
  • case expressions. Commented Jul 29, 2020 at 15:29

2 Answers 2

1

You can't use category in the next CASE expression.
But you can apply the same logic with the previous CASE:

select
  case when id  is not null then 'High' end as category,
  case when id  is not null then 'True' else 'False' end as flag
  ..........................

because category is not null when id is not null.
I removed else null from the 1st CASE expression because it is not needed since it is the default functionality to return null when none of the conditions in the when branches is satisfied.

Sign up to request clarification or add additional context in comments.

Comments

0

how about , ( you can simply use the id again to determine flag or if you say you cannot, just add a outer clause and use category there )

SELECT
 CASE
    WHEN id IS NOT NULL THEN
     'High'
    ELSE
     NULL
 END AS category,
 CASE
    WHEN id IS NOT NULL THEN
     TRUE
    ELSE
     FALSE
 END AS flag
FROM   goes here ---
JOIN   STATEMENT goes here ---

OR
    
SELECT
CASE
    WHEN category IS NOT NULL THEN
     TRUE
    ELSE
     FALSE
 END AS flag
FROM
( 
  SELECT
   CASE
      WHEN id IS NOT NULL THEN
       'High'
      ELSE
       NULL
   END AS category,
  FROM   goes here ---
  JOIN   STATEMENT goes here ---
)

1 Comment

In case of both option I agree to the point of @forpas about removing the else part first case statement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.