Beast Mode for Sum Function

Hi All,

I am using the sum function below which is throwing an error..can you please advise..


CASE WHEN YEAR(`DATE`) = year(CURRENT_DATE()) THEN SUM(`CURRENT_INVENTORY`,`NONCURRENT_INVENTORY`,`OLD_INVENTORY`) END

Best Answer

  • GrantSmith
    GrantSmith Coach
    Answer ✓

    SUM only takes a single argument. You'll need to add them together. Note that I'm adding 3 sums together as it will handle nulls otherwise if I add CURRENT_INVENTORY + NONCURRENT_INVENTORY + OLD_INVENTORY and if any one of those values is null then the entire value will be null causing incorrect summations.

    SUM(CASE WHEN YEAR(`DATE`) = year(CURRENT_DATE()) THEN `CURRENT_INVENTORY` ELSE 0 END)
    +
    SUM(CASE WHEN YEAR(`DATE`) = year(CURRENT_DATE()) THEN `NONCURRENT_INVENTORY` ELSE 0 END)
    +
    SUM(CASE WHEN YEAR(`DATE`) = year(CURRENT_DATE()) THEN `OLD_INVENTORY` ELSE 0 END)
    
    **Was this post helpful? Click Agree or Like below**
    **Did this solve your problem? Accept it as a solution!**

Answers

  • GrantSmith
    GrantSmith Coach
    Answer ✓

    SUM only takes a single argument. You'll need to add them together. Note that I'm adding 3 sums together as it will handle nulls otherwise if I add CURRENT_INVENTORY + NONCURRENT_INVENTORY + OLD_INVENTORY and if any one of those values is null then the entire value will be null causing incorrect summations.

    SUM(CASE WHEN YEAR(`DATE`) = year(CURRENT_DATE()) THEN `CURRENT_INVENTORY` ELSE 0 END)
    +
    SUM(CASE WHEN YEAR(`DATE`) = year(CURRENT_DATE()) THEN `NONCURRENT_INVENTORY` ELSE 0 END)
    +
    SUM(CASE WHEN YEAR(`DATE`) = year(CURRENT_DATE()) THEN `OLD_INVENTORY` ELSE 0 END)
    
    **Was this post helpful? Click Agree or Like below**
    **Did this solve your problem? Accept it as a solution!**
  • MichelleH
    MichelleH Coach
    edited July 2022

    @ozarkram You cannot have multiple fields inside the same SUM() function. Try changing to this:

    CASE WHEN YEAR(`DATE`) = year(CURRENT_DATE()) 
    THEN `CURRENT_INVENTORY` + `NONCURRENT_INVENTORY` + `OLD_INVENTORY` 
    END
    


  • Thank you so much @GrantSmith and @MichelleH ..Really appreciate your help!

  • ST_Superman
    ST_Superman Domo Employee

    @ozarkram - I think that @GrantSmith 's approach is a better option here. He has included safeguards for any null values. If you choose @MichelleH's solution you will get a null value if any of the three fields are null.