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
488 views
in Technique[技术] by (71.8m points)

tableau api - How to write an IF statement in SQL to hide the non duplicated row

Thank you for looking into this, and much is appreciated.

I would like to have an additional column called "SHOW_or_HIDE" where I can add the filter feature in Tableau.

Below is my SQL table for my Tableau and I want to create an IF statement base on if the same quarters has BOTH types "POR" AND "CWV" then I want to categorize it "SHOW" BUT if it only shows ONE either POR or CWV in a quarter then "HIDE". Basically, I only want my tableau bar chart to show a full quarter with POR & CWV only and if the quarter has only ONE of either POR or CWV I would like to hide but still have an option to show them in Tableau.

I'm extremely new to SQL so I'm having difficulty on how to nest it also.

Current Table

SCENARIO TYPE QUARTER PROGRAM GEO UNITS SHOW or HIDE
(4) FY20-Q1_POR POR FY20-Q1 XYZ USA 2 HIDE
(3) FY20-Q2_CWV CWV FY20-Q2 XYZ USA 1 show
(4) FY20-Q2_POR POR FY20-Q2 XYZ USA 5 show
(3) FY20-Q3_CWV CWV FY20-Q3 XYZ USA 3 show
(4) FY20-Q3_POR POR FY20-Q3 XYZ USA 4 show
(3) FY20-Q4_CWV CWV FY20-Q4 XYZ USA 9 HIDE
(3) FY21-Q1_CWV CWV FY21-Q1 XYZ USA 1 show
(4) FY21-Q1_POR POR FY21-Q1 XYZ USA 1 show
etc
question from:https://stackoverflow.com/questions/65925385/how-to-write-an-if-statement-in-sql-to-hide-the-non-duplicated-row

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

1 Reply

0 votes
by (71.8m points)

Might not be the best solution.

But the idea is to LEFT OUTER JOIN on distinct quarters for each type and then check for NULL values.

Written in MS Access, so the actual SQL might slightly differ (iif function).

select 
    iif (type = 'CWV', '(3) ' + bc.quarter + '_' + type, iif(type = 'POR', '(4) ' + bc.quarter + '_' + type, null)) as scenario,
    type,
    bc.quarter,
    program,
    geo,
    sum(ca) as units,
    iif(cw.quarter is not null and por.quarter is not null, 'SHOW', 'HIDE') as show_or_hide
from (
    bc_reports as bc 
    left outer join (select distinct quarter from bc_reports where type = 'CWV') cw on bc.quarter = cw.quarter
)
left outer join (select distinct quarter from bc_reports where type = 'POR') por on bc.quarter = por.quarter
group by bc.quarter, type, program, geo, cw.quarter, por.quarter
order by 3, 2

Output


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

1.4m articles

1.4m replys

5 comments

57.0k users

...