Wednesday, July 15, 2015

Coding Case Statement Made Easy

The title seems to imply that coding case statement is not easy. It's actually more tedious than difficult. It's mechanical, manual and repetitive. The more options in the statement, the worse it gets.

Let's use a recent example where the expected case statement is as follows:
Manually writing the above code is quite tedious. Moreover, manual coding those options is error prone. Using tools to help generate clean code can avoid those errors and save time in debugging.

There are two ways by which we can make it much easier to generate the code.

1.By Excel
Copy the values of [Measures] using menu Analysis>View Data and paste them in Column A. And use Concatenate() function to generate Column B:
  • Concatenate("WHEN '",A1,"' THEN SUM([",A1,"])")
2.By Tableau
Yes, by creating a calculated field. See the picture below:
Then we need to copy the generated code to the formula editor. To do this, go to Analysis>View Data. Copy the column that contains the code. Then paste it to the formula editor for calculated fields.

Note that, when the dimension of interest is [Measure Names], we can't directly create a calculated field from it. Then use this process:
1.Drag Measure Names to Rows and Measure Values to Text shelf.
2.Go to menu Analysis>View Data to copy the column Measure Names
3.Ctrl-V (Paste) it to a new sheet and create the calc field there.

BTW, this applies to some of the if..elseif..elseif statement as well, as long as it is uniform in format.

Hope this help save you a few minutes of your life!

2 comments:

  1. Thanks for sharing. How to write the code in this scenario?

    case 'Measures'

    when 'A' use 1

    when 'B' use 2

    when 'C' use 3

    end

    Here we have a static value, but we need the measure which increases its value by one for every case , then how to proceed ?

    Thanks !!

    ReplyDelete
    Replies
    1. Two methods:
      1.In Excel, create one column for Measure Names and another column for 1,2,3,.. Then create a formula to generate the case statement code.

      2.In Tableau, the 1,2,3 column can be created using Index() function. Then create a formula to generate the case statement code.

      Delete