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,"])")
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.
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!
Thanks for sharing. How to write the code in this scenario?
ReplyDeletecase '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 !!
Two methods:
Delete1.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.