0

I am creating a data analytics dashboard.I pass a parameter named channel_param to MySQL data-source.

I want to add an if statement in this query that first checks if the channel_param parameter value is equal to "ALL"

In case of "ALL", the following query should execute :

SELECT 
c.CountryCode, COUNT(f.`country_code_id`) AS view_count  
FROM 
fact_access_logs_views f
JOIN dim_country_code c ON f.`country_code_id` = c.`country_code_id` 
JOIN dim_time_access d ON f.`access_time_id` = f.`access_time_id`
JOIN dim_channel chn ON f.`channel_id` = chn.`channel_id

In case of any other value, this query should execute:

SELECT 
c.CountryCode, COUNT(f.`country_code_id`) AS view_count  
FROM 
fact_access_logs_views f
JOIN dim_country_code c ON f.`country_code_id` = c.`country_code_id` 
JOIN dim_time_access d ON f.`access_time_id` = f.`access_time_id`
JOIN dim_channel chn ON f.`channel_id` = chn.`channel_id`
WHERE 
chn.`shortname_chn` = ${channel_param} 

How can I achieve this ?

Danish Bin Sofwan
  • 476
  • 1
  • 6
  • 21

1 Answers1

0

This is how I solved the problem, using SQL CASE expression.

SELECT c.CountryCode, COUNT(f.`country_code_id`) AS view_count  FROM fact_access_logs_views f
  JOIN dim_country_code c ON f.`country_code_id` = c.`country_code_id` 
  JOIN dim_time_access d ON f.`access_time_id` = f.`access_time_id`
  JOIN dim_channel chn ON f.`channel_id` = chn.`channel_id`
WHERE chn.`shortname_chn` LIKE 
CASE WHEN 
         ${channel_param} = "ALL" THEN '%%' ELSE ${channel_param} 
END 

I hope this answer helps people facing the same confusion in future.

Danish Bin Sofwan
  • 476
  • 1
  • 6
  • 21