"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > SQL filters cash values ​​by date and sums

SQL filters cash values ​​by date and sums

Posted on 2025-04-18
Browse:623

How to Filter Cash Values by Date in SQL for Total Summation?

Totaling Cash Values with Date Filtering in SQL

As you mentioned, you have a SQL statement that calculates the total cash for each unique transaction ID using the following line:

select sum(cash) from Table a where a.branch = p.branch and a.transID = p.transID) TotalCash

To modify this statement to only total cash values that have a value date within the last month, you can update it in the following way:

select SUM(CASE WHEN ValueDate > @startMonthDate THEN cash ELSE 0 END)
from Table a where a.branch = p.branch and a.transID = p.transID) TotalMonthCash

Explanation:

  • CASE WHEN...THEN...ELSE...END: This is the searched CASE expression syntax, which compares a Boolean expression (in this case, ValueDate > @startMonthDate) to a set of results. If the Boolean expression is true, it returns the cash value; otherwise, it returns 0.
  • SUM(): This function is used to calculate the total of the cash values that meet the date filtering criteria.

Performance Optimization:

As a side note, if the performance of your query becomes an issue, consider rewriting it using a JOIN and GROUP BY instead of a dependent subquery. This can potentially improve the execution time.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3