Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

sql - Simplify nested case when statement

Below is my current SELECT CASE statement:

SELECT CASE 
WHEN edition = 'STAN' AND has9 = 1 THEN '9'
WHEN edition = 'STAN' AND has8 = 1 THEN '8'
WHEN edition = 'STAN' AND has7 = 1 THEN '7' 
WHEN edition = 'STAN' AND hasOLD = 1 THEN 'OLD'
WHEN edition = 'SUI'  AND has_s9 = 1 THEN 'S9' 
WHEN edition = 'SUI'  AND has_s8 = 1 THEN 'S8' ELSE 'S7' END AS version

I do not always want to repeat the edition = 'xxx' condition, such as

CASE WHEN edition = 'STAN' AND has9 = 1 THEN '9' ELSE WHEN has8 = 1 THEN '8' ELSE WHEN has7 = '7' ELSE WHEN edition 'SUI' AND has_s9 = 1 THEN 'S9' ELSE ...

In Excel this is fairly easy but how can I compile that in PostgreSQL?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this

SELECT CASE 
WHEN edition = 'STAN' THEN 
     CASE 
          WHEN has9 = 1 THEN '9'
          WHEN has8 = 1 THEN '8'
          WHEN has7 = 1 THEN '7'
          WHEN hasOLD = 1 THEN 'OLD'
     END
WHEN edition = 'SUI' THEN
     CASE 
          WHEN has9 = 1 THEN 'S9'
          WHEN has8 = 1 THEN 'S8'
     END
ELSE 'S7' END AS version

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...